The last days I was busy with writing an article on the vertical centering of HTML elements. This issue which seems simple at first, in fact is very complicated in cases a lot of problems for the many web developers. I tried to provide a well-ordered explanation of the existing centering methods, especially the most universal and reliable of them. However, even the best explanation worth nothing without practical examples and it’s a time to say a big thanks to CodePen! This really amazing tool which I started to use not long ago saved me a lot of time in the samples preparation and finally allowed making them as good as I probably wouldn’t be able to make without it at all.
Now my article named Vertical centering of elements in HTML is ready and available for reading. Although it wouldn’t be correct to repeat it here, I’d like to give a short a short summary of its most important points.
Apart from some ugly tricks, there are two really universal and reliable centering methods: the CSS Table Layout and the Flexible Box Layout model.
The first one came from the HTML 4 days when the use of tables was a primary method of web page layout. The HTML 5 standard provides the possibility to keep using this concept in a little bit more elegant way which may be called “tables without tables”. The CSS ‘display’ property of almost any HTML element can be set to the value ‘table’, ‘table-row’ or ‘table-cell’ and then it will act as a corresponding element of table. In particular, the property ‘vertical-align’ which in the most cases doesn’t works well in many other circumstances work fine with such elements. Being supported by all the modern browsers, the table layout can be used on any platform with no doubts about the compatibility.
The second method is fresher, more straightforward and requires writing much less of code. By setting the ‘display’ property of an element to ‘flex’ or ‘inline-flex’ we gain an access to the smart flexible model’s alignment and justification which doesn’t require insertion of additional elements as the table base layout does. However, the Flexible Box model officially is still in the draft mode and is not supported by some browsers on the mobile platforms.
The below code demonstrates how to use the both methods in the following common cases:
- Single and multiple lines of text
- The images
- Textboxes with wrapped images
- Buttons and menus with icons and text
- Input controls with text labels