Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

actually I saw many questions like this but I can't found normal answer of this question because that I open this question again.

When we have block element(display: block) this element contain full width of parent component if element itself root element this element width take 100%.

But when we look block element(display:block) but position absolute elements there are work like inline-block elements(work like block element but width not full of parent component) even parent element position relative.

Can anyone explain me why position absolute and fixed elements width not work like display: block elements.

https://jsfiddle.net/epbkmzh3/28/

    <div class="container">
      <div style="background: red;"> 1 </div>
    </div>
    
    
    <div class="container" style="position: relative;">
      <div style="position: absolute; background: red;"> 1 </div>
    </div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
393 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's because absolute and fixed positioning removes the element from document flow.

And since those elements are removed from document flow, there is no reference for what width they should be, so they only take as much space as their content.

They are still "block" elements if they are inherently block elements (div, p, etc.), unless the display property is changed via CSS. Edit for clarity: The browser will still compute as display: block even if the display property is changed via CSS.

Here is some documentation on document flow: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout/In_Flow_and_Out_of_Flow

The important part:

Taking an item out of flow

All elements are in-flow apart from:

    floated items
    items with position: absolute (including position: fixed which acts in the same way)
    the root element (html)

Out of flow items create a new Block Formatting Context (BFC) and therefore everything inside them can be seen as a mini layout, separate from the rest of the page. The root element therefore is out of flow, as the container for everything in our document, and establishes the Block Formatting Context for the document.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...