Home > Software design >  question about width of an absolute positioned element
question about width of an absolute positioned element

Time:12-28

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 >
   <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?

CodePudding user response:

It is still a child of the parent, but it is also outside the flow. Giving the parent position: relative; will allow certain properties on the child (like top, etc) to still act relative to the parent. Usually absolutely positioned elements require explicit height and width declarations, but it depends on what you are trying to do...

CodePudding user response:

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.

  • Related