Vertical align

How to Vertically Align Anything with CSS

April 23, 2018|CSS

Whether you’re an established web developer or new to creating websites you may have thought you knew how to vertically align… for a minute. But don’t worry, it happens to us all.

Here’s my three favorite ways to vertically align stuff in css.

Transform

If you’ve been doing web development for a while you’re no doubt familiar with this approach. Before flexbox or css grid this was the only sure way to vertically align in css. Don’t let that fool you though, I still use it today.

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

If you find when using this approach that elements become blurry because they’re placed on a half pixel, try this:

 .parent {
    position: relative;
 }
 .child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: perspective(1px) translate(-50%, -50%);
 }

Flexbox

To center an object using flexbox you just need two centering properties:

.element {
     display: flex;
     justify-content: center;
     align-items: center;
 }

CSS Grid

This is such an easy way to center something. This will center the immediate child of this element. If, there are five children inside this element and each of the children have two children. It will center only the five children (not the two nested inside).

.element {
   display: grid;
   place-items: center;
   height: 100vh; // or however tall you want your box to be
 }

Aligning just one line of text?

If you are simply trying to vertically align text inside some element it is much easier. All you need to do is give the text the same line-height as the container it’s in.

For example, if the text is inside a button and the button is 32px tall. Just give the text a line-height of 32px and it will be vertically centered.

.button {
    height: 32px;
 } 
 .text {
   line-height: 32px;
 } 

I hope this helps you as you center things in CSS. Which method did you end up going with? Let me know.

Want to level up your CSS skills?

Sign up below to receive a CSS tip each week as well as access to my courses and articles as they become available.

I won't send you spam, promise. If it ever feels that way you can unsubscribe at any time.

Sign Up For Free

×

Sign In

×