I am not looking for a different solution to the question of centering elements; I am looking for an explanation why the solution presented here doesn’t work.
Consider the following jsFiddle:
Here’s the HTML/CSS code for reference:
HTML
<div class='outer'>
<div class='middle'>
<div class='inner'>
Text should be centered
</div>
</div>
</div>
CSS
.outer {
position: absolute;
left: 200px;
top: 50px;
width: 100px;
height: 100px;
border: 2px solid #00f;
border-radius: 10px;
}
.middle {
position: absolute;
left: 50%;
top: 50%;
line-height: 1em;
}
.inner {
position: relative;
left: -50%;
top: -50%;
width: 5em;
}
The element inspector in both Chrome and Firefox tell me that both middle
and inner
have the correct width and height, and indeed the horizontal positioning is working correctly, but for some reason the top: -50%
rule is ignored. However, it is only ignored if .middle
doesn’t have an explicit height — if you add one, it works, even if the effective height is the same as what it is already. Why is this?