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>
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.
See the link below. I believe you're going to have a better result with Fixed for what it is you're trying to do, although I'm still not 100% sure I understand what that is.
http://jsfiddle.net/8q107wvb/1/
body {background:#e9e9e9; color:#202020;}
#wrapper {width:500px; background:#fff; margin:50% auto;}
.centered-content {position: fixed; top: 50%; left: 50%; background:#fff; padding:20px;}