1

Why When div with position relative does not have parent div does not height in percent work?If position absolute it work

   <div style="position: relative;
        width:50%;
        height: 50%;
        background-color:black;">

      </div>
    
   

2 Answers2

1

See the specification:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

So when you set position: relative and, as is this case, the height of the parent isn't specified, then it gets treated as height: auto.

An absolutely positioned element, assuming there is no other containing block in the way, will have the viewport as its containing block, and that has a known height.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Position relative means it will be positioned relative to its normal position from its parent. If your div does not have a parent that has a fixed height, your div does not know how big it has to be, if its on percentage, it doesn't have a parent to relate to.

As a direct result, the top with a percentage would not have any effect either.

On the other hand, position absolute will be positioned relative to the nearest positioned ancestor. However; if an absolute positioned element has no positioned ancestors, it uses the document body, which is why it works on yours.

Jaocampooo
  • 482
  • 3
  • 10