Vertically Align Anything

For this first week I want to give total props to Sebastian Ekström over at zerosixthree.se. He wrote an amazing blog post that has spurred me on to share this snippet even more.  Shall we begin?

…… Dramatic Pause ……

I think so!

Have you ever been in a situation where you just wanted to vertically align an element in the center of something and didn’t want to write out a bunch of code to do so? A year ago I found one of the most helpful code snippets I have ever found. Sebastian Ekström zerosixthree.se wrote an amazing post that shows by using the power of transform: translateY, you can vertically center align the way you have always dreamed of … with three lines of code (plus vendor prefixes)!

To do this we write:

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

To take this a step further we can use the power of SASS and write it as a mixin.

@mixin vertical-align {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}

Then the only step you need to make after that is to add this to it’s parent container (this keeps things crisp):

.parent-element {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}

Again an even better way to do this would be to make it a mixin:

@mixin parent-vertical-align {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}

Taking it a step further:

If you are wanting to help reduce bloat within your code (which I highly advise), you could use the SASS placeholder selector like so:

%parent-vertical-align {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}

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

.incredible-parent-element {
@extend %parent-vertical-align;
}

.awesome-child-element {
@extend %vertical-align;
}

And that’s it folks!

Demo:

Create. Stop. Be Creative.