how to center a div created dynamically with posit

2019-08-10 19:54发布

str.Append("<div class=\"rect\" style=\"top:" + (rectangles.ElementAt(i).Y + 50).ToString() + "px;left:" + (rectangles.ElementAt(i).X + 50).ToString() + "px;width:" + (rectangles.ElementAt(i).Width - 1).ToString() + "px;height:" + (rectangles.ElementAt(i).Height - 1).ToString() + "px;position:absolute;\"</div>");

I am creating this div and more divs that has been positioned absolute and then send the created html to another div(container). So that it creates a map the image is attached

enter image description here

标签: html css
1条回答
祖国的老花朵
2楼-- · 2019-08-10 20:22

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:

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

HTML with dynamic dimensions:

<div class="bd_container">
  <div id="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

查看更多
登录 后发表回答