Search code examples
htmlcsswidthcss-positionabsolute

question about width of an absolute positioned element


I'm new in CSS. I don't understand if a display: absolute; element for instance a , is still consider child of its parent or not (for its out of the flow)?

For example:

**HTML**

<div class="container">
   <div class="my_div">
       Lorem ipsum dolor sit amet, consectetur adipiscing elit.
       In sit amet nibh et arcu gravida tincidunt. Nam dignissim elit
       vitae erat porta, at efficitur lacus consequat. Sed molestie,
       mi a efficitur elementum, lacus metus hendrerit libero, posuere
       ultricies urna libero nec quam. 
   </div>
</div>


**CSS**

.container div {
   width: 50%;
}

.my_div {
   position: absolute;
}

without the position: absolute; my_div width is equal to the 50% width of the container . But after the setting position: absolute; I don't understand what actually happen to the my_div width, is still referring to the CSS .container div{} rule or not?


Solution

  • The "parent-child relationship" doesn't really change (so technically it'll still be a child thereof, which you can see reflected in the DOM), but the "(document) flow" does indeed change.

    Once you use position: absolute; the element is removed from the normal document flow, which does affect the effect many properties have (as you've likely noticed).


    Since you mentioned being new to CSS, i should make sure you're aware that 90% of the time, when online tutorials (or books) suggest using properties such as position and float, they are likely to be leading you down an outdated and/or misguided path.

    Nowadays we have things like flexbox (display: flex) and grid (display: grid) which make the vast majority of layout challenges (which used to be a pain to understand/create) totally simple.