2

I am trying to understand positioning of elements in html. The accepted answer here says,

"All elements that are position:absolute; are automatically treated as display:block, since that's the only logical display mode for absolute positioning."

Is this always true? If display is always block for absolute elements, why the following code snippets appear differently? Please help me to understand this. thanks.

 <div>
    <div style="display:inline-block;">aaa</div>    
    <div style="position:absolute;">bbb</div>
    <div style="display:inline-block;">ccc</div>     
    </div>
    
    <br><br>
    <div>
    <div style="display:inline-block;">aaa</div>    
    <div style="position:absolute;display:inline-block;">bbb</div>
    <div style="display:inline-block;">ccc</div>    
    </div>
Kiran
  • 896
  • 1
  • 6
  • 25

2 Answers2

4

There's a couple of things here. First, no, not all absolute positioned elements are treated as display:block. Their display value is blockified which means that they are converted to block-level display values. For example:

display:inline-flex => display:flex
display:inline-grid => display:grid
display:inline-table => display:table
display:inline list-item => display:list-item (Firefox supports inline list-item)

display:none and display:contents aren't changed.

display:inline, display:inline-block, and internal table object boxes => 
display:block

Elements that are already block level are unaffected. Flex is still flex, grid is 
still grid, etc.

However, that doesn't explain why you get different results for your two cases, since in each case the absolute positioned items do indeed have a computed display value of block. For this, we need to address our expectations of what it means for an element to be display:block. We expect it to start a new line and have its left to right margin edges fill the width of the containing block.

In fact, that only applies to block level elements in normal flow. Absolute positioned elements are not in normal flow, and so those rules don't apply. They have their own set of rules, part of which say that if their top, left, bottom, right values are auto (which they are in your examples), the box is positioned according to where its position would have been if it hadn't been absolutely positioned. And if it hadn't been absolutely positioned, the display:block and display:inline-block difference would have had an effect, in your first case starting a new line, in your second case remaining on the same line.

Alohci
  • 78,296
  • 16
  • 112
  • 156
3

The default behavior of position: absolute is display:block, but you override that default behavior when you add display:inline-block;.

A. Meshu
  • 4,053
  • 2
  • 20
  • 34
Ejiofor
  • 31
  • 1