Vertical centering has always been a fairly elusive goal when building CSS layouts, but it’s actually easier to achieve than you might think. Here are the two simplest methods that I know of to achieve this goal – one uses two old, yet underused, values for the
display property and the other uses the new Flexible Box Layout (or ‘Flexbox’) that is available in CSS3.
For both methods I will take this HTML:
and centre align the inner div vertically and horizontally. Horizontal alignment is easy of course, so the real point of this is to get the div centre aligned on the vertical axis.
The first method uses
display: table and
display: table-cell to achieve the vertical alignment goal. These values have been around for ages and will work in any browser. Some people may balk at using the
display property like this because of the current popular aversion to tables, but I assure you it is a semantically correct and legitimate use of the property. The CSS for it, when applied to the above HTML, is quite simple and looks like this:
table-cell properties cause the browser to treat the elements as if they were part of a table, causing the
vertical-align property to become applicable.
The second method uses the flexbox model that is outlined in the latest CSS3 spec. It is still under review and subject to change, but it currently works in the latest versions of all browsers except Opera (yes, it even works in IE9). It does use browser-specific properties unfortunately, but in time they will be able to fall away. The CSS for it is as follows:
In this example, the
box-pack property aligns the element horizontally, while the
box-align property is what sets the vertical alignment.
As you can see, with this way of doing things only the parent element needs to have any CSS applied to it – I would argue that this is more semantically correct as you can then apply the actual content styles without worrying about any of the positioning for the element. Also, without the browser-specific properties, this method is far shorter and more simple to apply.
While the flexbox method maybe be shorter, easier and more semantically correct, it will be a while before it is widely accepted. The browser-specific properties help and will make sure you can use this method relatively safely, but, as with so many of the new properties in CSS, it is generally safer to stick with the older way of doing things for now. That’s where the first method comes in – it works in all browsers and is entirely reliable. It may be slightly longer, but it is still very easy to implement and won’t cause any issues.