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.


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!


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!

Mantaining a fluid element aspect ratio with CSS pseudo-elements

Do you ever wondered how to scale a div within a fluid layout, keeping its aspect ratio?

The solution is pretty easy, and – amazingly – you don’t need Javascript

Just nest your element in a fluid container – this will be our ratio-killer – and give it these rules:

.container {
  position: relative;
  display: inline-block;
  width: 50%;

These properties will let our container div to scale accordingly to the parent element width. Then, we’ll use CSS3 pseudo elements on the container to do the magic:

&:before {
content: "";
display: block;
padding-top: 145%;

The padding-top will represent the height of our div. So tweak the percentage accordingly to the desired aspect ratio!

Finally, we’ll place the element for the contents and give it absolute positioning:

.inside-content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;

And voilà! The trick is done: we now have a fluid element that scales keeping its aspect ratio.

Want to give it a ride? Here’s an example: