The Ultimate CSS Vertical Align Tip

The Ultimate CSS Vertical Align Tip

It often seems like a lot more effort than necessary when aligning things vertically in CSS, especially when using responsive designs. This CSS vertical align tip shows you a quick solution, using just three lines of CSS (excluding vendor prefixes).

Unless using CSS tables and vertical-align: center; – aligning things centrally usually involves setting a fixed height, then using top: 50%; – then you have to give it a negative margin-top of half the fixed height. This is a lot of code to do something simple – and what happens if the thing you’re aligning vertically doesn’t have a fixed height? The answer, as usual, is a jQuery workaround – more effort.

Everything above is what I used to use for aligning text on a ‘splash screen’ if you like, and it did work well – but now I’ve updated my existing code using this new method, due to its ease of use. It even works in IE9!

The Ultimate CSS Vertical Align Tip

So, enough with the chat – here’s the code:

.element {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}

As with the old method, we still need top: 50%; but we no longer require a fixed height. No matter what the height of your element, even if it’s a percentage, the transform: translateY(-50%) will move the element back up by half of its height – aligning it centrally.

All of the vendor prefixes are included, so this trick should work in nearly all browsers, including IE9! It works for text, images, multiple lines of text – almost anything can now be vertically aligned easily.