Setting CSS top percent not working as expected

Define a dimension for the parent container, e.g. div:

<div style="border: 2px solid red;position:relative;top:0%;left:0%;height:200px;width:300px">
    <div style="border: 2px solid green;position:absolute;top:50%;left:50%;height:50%;width:50%">
    </div>
</div>

Or

Another way is to just stretch the parent container, i.e. div, by its top, bottom, left, and right properties. Like this:

<div style="border: 2px solid red;position: absolute;top: 0px;bottom: 0px;left:0px;right:0px;">
    <div style="border: 2px solid green;position:absolute;top:50%;left:50%;height:50%;width:50%">
    </div>
</div>

Consider your original HTML:

html, body {
  height: 100%;
}
<div style="position:relative;top:0%;left:0%;height:100%;width:100%">
  <div style="position:absolute;top:50%;left:50%;">test</div>
</div>

The inner/child div has position: absolute, so it is out of the content flow of the parent element and will not contribute to the height or width of the parent element.

The parent div is in the content flow, but has no content, so its intrinsic height would be zero. However, you specified height: 100%, but this will not do anything because the div has no height reference on which to base a computed value. So the computed height value for the parent div is zero.

As a result, the child element's top offset computes to 50% of zero, so it is positioned at the top edge of the parent block.

You would need either to specify a height for the parent div or assign

html, body {height: 100%} 

as this would allow the div to compute its height based on the height of the body, which is based on the height of the html, which being 100%, takes that of the screen.

Tags:

Css