I want to center a div both horizontally and vertically using the method of using position absolute and left: -50% etc.
However, it will not become vertically centered, only horizontally.
The result is not centered vertically:
Why?
html
<div class="background">
1<br>2<br>3<br>4<br>5<br>6<br>
<div class="overlay">
<div>foobar</div>
</div>
</div>
css
.background
{
border: 1px solid black;
position: relative;
}
.overlay
{
position: absolute;
top: 50%;
left: 50%;
}
.overlay > div
{
background: #888;
color: #fff;
position: relative;
top: -50%;
left: -50%;
padding: 10px;
}
If I use margin-top: -50%
instead of top: -50%
in .overlay > div
, the foobar div moves too far upwards:
so apparently that height percentage is related to the background div.