Align vertically any element in CSS using translateY

If you’re reading this, you probably had to face – at least once in your life – the challenge of the vertical align in CSS.

image

There are many, many solutions. One could argue about which one is cleaner, more elegant, more compatible, and so on. Today I’ll just give you another option – you decide which one you like the most!

Yet another way to do it

Lately I’m using the translateY method.


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


The explanation is trivial: we position the element relatively and give it 50% top, pushing it down for the half of the container height. Then, we move it the half of its own height up. And.. That’s it!

image

You can find a live example here.

I like the simplicity and conciseness of this method, and I’m using it quite often. The only downside of this is that it only works on browsers that support CSS3 Transforms (basically > IE9).

If you don’t plan to support legacy browsers, give it a try!

Leave a Reply

wpDiscuz