Vertical Alignment: My New Favourite CSS Rule
Vertical alignment where you don’t know the heights and widths of anything. It’s a pain, right? My new favourite CSS rule (last year it was pointer-events: none) is the answer. Well, actually it’s 3 rules:
display: table; display: table-cell; vertical-align: middle;
The two ‘display’ rules allow you to turn your elements into table elements in all but name. This means that they will be no larger than the content that is within them, and will arrange themselves vertically (with the ‘table’ element as an outer container and the ‘table-cells’ all in a row inside of it).
Vertical-align is one of those rules that I never understood when I was starting out with CSS. It always looked like the answer to my (vertical alignment) problem, but it never did what I expected it to! Now, with ‘display: table’ in my corner, it does!
Want to see an example of this in action? Well, here you go!
We have three divs around a piece of text. My logic here is as follows:
- The outer container lets us simulate the situation where the width and height are unknown. Change the width and height values for the outer container to whatever you want, but the content it contains will always be vertically centered.
- The inner container is our table. I have added a width and height of 100%, otherwise you’ll find, as mentioned above, that it will only expand to the size of the content within it.
- The cell is our ‘table-cell’. Note the use of vertical-align, which ‘does the business’.
And that’s it! You have some nice vertically centered text, regardless of the width or height of the container or the text! Pretty simple really.
This works in everything from IE8 upwards. If you’re unfortunate enough to be working with anything lower, I’m afraid this isn’t going to be much help to you. You’re probably going to need to do something a bit dirty with conditional comments and padding. Sad times.
One day soon we’ll be able to use flexbox to do this. Unfortunately browser support isn’t quite there yet, so I won’t be using that for the forseeable future. Hence, my new favourite CSS rule(s)!