Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS position absolute/relative change outer div alignment

can someone explain me the reason why the red div container ("Label") is aligned at the bottom with position absolute as inner container and in case with position relative on the top. Why affect an inner div container an outer div container?

<div>
  <div style="position: relative; display:inline-block; height:auto; background: red">Label</div>
  <div style="position: relative; display:inline-block; height:100px; width:100px; background: blue">
  <div style="position: absolute; height: 20px; width: 20px">XXXX</div>
</div>

With inner div position absolute

<div>
   <div style="position: relative; display:inline-block; height:auto; background: red">
      Label
   </div>
   <div style="position: relative; display:inline-block; height:100px; width:100px; background: blue">
      <div style="position: relative; height: 20px; width: 20px">XXXX</div>
   </div>

With inner div position relative

like image 928
abc2016 Avatar asked Jan 25 '26 01:01

abc2016


1 Answers

The reason is, that display: inline-blockitems are treated as being positioned on one line (like text), per default their text content (more precisely: the last line of their text, at least as long as this is still inside the container) being aligned at the bottom.

When you change the third's DIV position to absolute, its text becomes independent from the parent DIV, instead the block itself is put in the top left corner of the parent DIV. Since now there is no "real text" directly in the second DIV, the bottom of the second DIV is aligned with the base line of the text (not sure about this expression in English) of the first DIV.

like image 106
Johannes Avatar answered Jan 27 '26 14:01

Johannes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!