« HE:labs

Doing vertical align on elements like a boss

Postado por Thiago Gonzalez em 25/02/2014

How often have you had to align text or element vertically into another? Which method do you usually use? See a "like a boss" solution for it :)

  • Line-height?
  • Position: absolute?
  • "Display: table" on the parent element and "display: table-cell" on the children?

The simplest method of doing this is using the "transform" parameter of CSS 3 in our favor. See:

1 position: relative;
2 top: 50%;
3 transform: translateY(-50%);

With this we don't need to define a fixed height for the parent element. Just need to declare this to the element that must be positioned to the center.

If you often use SASS, you can create this mixin:

1 @mixin vertical-align {
2   position: relative;
3   top: 50%;
4   -webkit-transform: translateY(-50%);
5   -ms-transform: translateY(-50%);
6   transform: translateY(-50%);
7 }

Now just apply to the element like this:

1 .wrap p { @include vertical-align }

The best notice: it's crossbrowser even in Internet Explorer 9!

What do you think about this method of centralizing elements vertically? Did you already know that? Comment here :)


Sabia que nosso blog agora está no Medium? Confira Aqui!