HornedReaper HornedReaper - 9 days ago 8
CSS Question

Setting CSS top percent not working as expected

I tried a responsive css layout,but "top:50%" can't work and the "left:50%" can.
Why it happened?

<div style="position:relative;top:0%;left:0%;height:100%;width:100%">
<div style="position:absolute;top:50%;left:50%;">
</div>
</div>

Answer

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>