DEV Community

Lauralee Flores
Lauralee Flores

Posted on

How to Vertically Align Anything with 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%);
}
Enter fullscreen mode Exit fullscreen mode

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%);
 }
Enter fullscreen mode Exit fullscreen mode

Flexbox

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

.element {
     display: flex;
     justify-content: center;
     align-items: center;
 }
Enter fullscreen mode Exit fullscreen mode

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
 }
Enter fullscreen mode Exit fullscreen mode

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;
 } 
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
jassehomar profile image
Omar Jasseh • Edited

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

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