Centering was very simple in the old days, where everything had a fixed size and content would (at most) be horizontally centered inside a DIV by using text-align:center. Nothing was simpler than that. Back in those good old days, everything was specified using a fixed number of pixels and developers could center content using that information by using paddings and margins.
But then, someone wanted to center things vertically as well as vertically. In most cases, “centering” meant having equal padding at the top and bottom of the container. Content pushed the bottom padding down to make room and still look centered. Still quite simple.
But what if the container had a fixed-height container and still had to center vertically a piece of content of unknown height? The equal-padding trick failed here as it would not render a fixed-height container. How can you center the content while keeping the container’s height intact?
Let CSS and its table layout come to the rescue! Instead of using actual HTML tables, you can specify a fixed height and pick display:table on the container. Then, you can use display:table-cell on the content itself to create a CSS-driven table layout. Finally, you added vertical-align:middle to the content and you will have your content centered no matter its height. Note that you should make the container big enough to let content fit in or it will expand automatically.
Centering in the dark
Table layouts come in handy when you know the container’s height but there are times when you don’t know anything about the container or the content and you still want it centered both horizontally and vertically.
With the advent of responsive website, little is known about the size of the display, so the previous centering solutions would provide limited success. How to proceed, then?
In this case, we can use CSS transforms (the translate transform to be precise) to let the inner content be centered inside the container. While CSS3 transforms can only be used on newer browsers, most of them already support them, making centering no longer a difficult feat.