Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How position absolute and fixed block elements get their dimension?

Tags:

html

css

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>
like image 642
Murad Sofiyev Avatar asked Feb 16 '26 23:02

Murad Sofiyev


1 Answers

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.

like image 116
disinfor Avatar answered Feb 19 '26 11:02

disinfor



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!