I know there are many ways to center things with CSS. Centering anything horizontally is quite straight forward. However, if you are going to center anything vertically, it is a whole new story. I just want to know why we can't just say bottom-align:auto; top-align:auto; as we do when we want something centered horizontally? Why does something which seems as simple as centering something seem so hard when centering something horizontally is that simple? I know there are many ways, but let's just say you have an element of an unknown size you want to center inside another element of unknown size.
I have been sitting with this for almost two days without finding a good question on this answer, we have tons of different ways to center items horizontally, but why has not one single CSS standard come up with a way to center this vertically? Is it a bad thing to do? Does it make people cry or randomly go into labor? Does it melt down nuclear reactors?
We live in 2014. It seems unnecessary to have to use Javascript in order to do something as simple as to center something inside another element.
Edit: Code sample of what I mean: http://jsfiddle.net/VsakD/
CSS:
div.parentbox
{
width:500px;
height:500px;
border-style:solid;
}
div.childbox
{
width:300px;
height:300px;
border-style:solid;
margin-left:auto;
margin-right:auto;
margin-top:auto;
margin-bottom:auto;
}
HTML:
<div class="parentbox">
<div class="childbox">
I shall be in the middle of parentbox regardless of its size!
</div>
</div>
line-height
to be equal to the parent's width. Otherwise, you could just use an offset margin with absolute positioning (Click here for a blog post all about absolute vertical positioning). Or, like @GCyrillus suggests, make the parentdisplay:table
and it's children todisplay:table-cell;vertical-align:middle
. – Jack