Skip to content Skip to sidebar Skip to footer

How To Center A Div Created Dynamically With Position Absolute

str.Append('

Solution 1:

You can enclose your dynamic <div> inside a parent <div> wide and tall 0 pixels and absolutely positioned at the center of the page with left: 50%; top: 50%;

CSS:

.bd_container {
  position: absolute;
  height: 0;
  width: 0;
  top: 50%;
  left: 50%;
}    

#bigdiv1 {
  position: absolute;
  height: 200px; /* Static height */width: 200px; /* Static width */background: blue;
  left: -100px;
  top: -100px;
}

#bigdiv2 {
  position: absolute;
  background: orange;
}

HTML with static dimensions:

<divclass="bd_container"><divid="bigdiv1"><!-- Replace with your div --><strong>Div 1</strong><br /> With static dimensions and centered
  </div></div>

HTML with dynamic dimensions:

<divclass="bd_container"><divid="bigdiv2"><!-- Replace with your div --><strong>Div 2</strong><br /> With dynamic dimensions and centered
  </div></div>

To positionate your dynamic <div> you can use jQuery's css() function like this:

var d2_width = parseInt($("#bigdiv2").css("width")) / 2;
var d2_height = parseInt($("#bigdiv2").css("height")) / 2;

$("#bigdiv2").css({
  "left": "-" + d2_width + "px",
  "top": "-" + d2_height + "px"
});

And here is a demo for you

Post a Comment for "How To Center A Div Created Dynamically With Position Absolute"