jet-640309_1280

The Best Way To Vertically Center with CSS

If there is one thing that’s truly annoying in CSS, it’s trying to vertically center an element inside a parent. You’d think vertical-align:center would work, but normally it doesn’t. display:table-cell often has other issues that need working out. So where does that leave us?

Enter transform. Most people only think to use transform to rotate or scale elements on a page, but you can also use it to just move things around on the x or y axis.

Here’s the code we need:

You’ll notice that it doesn’t need any specific height to work, in the element itself. A parent will need a height specified in px, em, or rem. But it doesn’t need to be the direct parent. If a grandparent is set to 240px, then the parent is set to 100%, this will still work.

And don’t forget your vendor prefixes on transform, because it’s too much to ask that they just support it.

I haven’t found a better or more consistent way to vertically align elements.

Awesome code found here. Check it live on CodePen.

Leave a Reply