Positioning and Margins

Child Element
Child Element
Container outlined in yellow
<div id="parent">
  <div class="container">
    <div class="child"></div>
    <div class="child"></div>
#parent {
  height: 300px;
  position: relative;

.child {
  height: 100px;

#container {
  position: absolute;
  top: 50%;
  left: 50%;

onload=function() {

  var container = document.getElementById("container");
  var divWidth = container.offsetWidth;
  var divHeight = container.offsetHeight;
  container.style.marginTop = -divHeight / 2 + "px";
  container.style.marginLeft = -divWidth / 2 + "px";


To center the container this method:

Because the height of the container is unknown and dynamic, Javascript is used to get the value and set the negative margin.

Note: This method assumes the height of the parent element and each child element is fixed and known. However, the number of child elements is unknown and the total height of child elements is dynamic.

Additional styles not related to the above have been used to make this demo more presentable.