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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…