DEV Community

loading...

How to Vertically Align Anything with CSS

flores8 profile image Lauralee Flores ・2 min read

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.

Discussion

pic
Editor guide
Collapse
jassehomar profile image
Omar Jasseh

you forgot to mention something when using flexbox, centering everything to the middle of the parent container does not just work like that, for the align-items: center to work the flex container should have a height defined. Eg: min-height: 100%

Collapse
nickytonline profile image
Nick Taylor (he/him)

Didn't know about place-items: center; for CSS grid. Thanks for sharing.