Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

html - How position absolute and fixed block elements get their dimension?

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

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

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...