简体   繁体   中英

Centering div in parent div when both have position absolute

I generate my components dynamically with JS, using position: absolute for both parent's and children, as this gets the placement how I want it.

However, every solution I've seen for centering a div within a div requires position of one to be relative, is there a way around this?

Any help appreciated.

Starting from two divs:

<div id="div1">
  div 1
  <div id="div2">
    div 2
  </div>
</div>

with jquery:

let offset = $('#div1').width() / 2 - $('#div2').width() / 2;
$('#div2').css('left', parseInt(offset) + 'px');

without jquery:

let offset = (document.getElementById("div1").clientWidth / 2) - (document.getElementById("div2").clientWidth / 2);
document.getElementById("div2").style.left = parseInt(offset) + 'px';

You can apply the following CSS to your 2nd div to get it centered.

left: 50%;
transform: translateX(-50%);

However, this will only work with relatively modern browsers. 'transform' is a CSS3 property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM