There is a relatively clean way to center an HTML element of variable dimensions within a container using CSS and without using tables.
An interesting article and demonstration of, as the author calls it, Absolute Centering in CSS has received a lot of attention on Hacker News and has enticed me to present the way I vertically and horizontally center elements in CSS. I have been wanting to write about this for quite a while now, but this seems like a very opportune moment to do so.
Disclaimer: I am not the originator of this method. I have read about it years ago on a couple of websites I don’t recall.
For those of you who are only interested in seeing some code in action check out this fiddle.
The problem with the method presented in the aforementioned article is that it requires the height of the element to be declared. This can be avoided by adding
display: table to the rule but this only works in some browsers.
Beginners in the arts of Cascading Style Sheets expect the
vertical-align property to achieve the desired result and believe it or not this same property is at the heart of the method I am presenting. Aside from table-cell elements, the property also applies to inline-level elements. That means elements that are either
Now consider a container with two child elements with
display: inline-block and
vertical-align: center. If one of them is the same height as the container, the other one will end up vertically centered. Add
text-align: center to the container and, assuming that the full-height element is empty, you now have an element that is centered both vertically and horizontally. Even better, as can be seen from the example fiddle, a pseudo-element can be used instead of the unneeded element.
Is this amazing or what?