Skip to main content
CSS Tip

100 ways to center an element horizontally and vertically

Centering in CSS is pretty easy nowadays. We have numerous methods to do it, but how many exactly? I did the count, and I was able to reach 100 different ways!

css-generators.com/center/

The list includes old and obsolete methods (that you should not use), but it was a fun exercise trying to enumerate all the possibilities.

Which method should I use?

I don't recommend choosing a single method to always use. Instead, consider the layout you are working with and select the appropriate code. It's crucial to understand what each code is doing because not all of them are the same. To help you with this, you can check my exploration to understand the fundamentals of alignment in CSS.

That being said, here are my favorite methods for centering a single element horizontally and vertically for each type of layout.

.container { 
display: block;
align-content: center;
justify-items: center; /* the support is still not good for this one */
}
.container {
display: grid;
place-content: center;
}
.container {
display: flex;
flex-wrap: wrap;
place-content: center;
}

One advantage of these methods is that they can also be used to center multiple items (under certain conditions). For this reason, I am considering only the container (and not the item) when defining the alignment properties.

See the Pen Centering multiple items by Temani Afif (@t_afif) on CodePen.

The flex approach is interesting because it's the only one that places the items horizontally and switches to a vertical configuration when the container is narrowed.


More CSS Tips