Three lines of CSS to center anything horizontally and vertically

Amit Merchant · January 4, 2021 ·

Oftentimes, I stumble across a situation where I would need to center something and over the years I have tried different permutations and combinations. But all those somehow felt “hacky” and not something that is reliable.

But then, recently I learned about this little trick which only requires three lines of CSS to center anything, horizontally and vertically. That too in a proper way! Check out the below CodePen first.

See the Pen Center anything by Amit Merchant (@amit_merchant) on CodePen.

As you can see, to center anything horizontally and vertically inside a container element, you would only need to give the following CSS to it like so.

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

The flex property allows the container to have flexible items, the align-items property would center the content on the y-axis while the justify-content would center the content on the x-axis.

And that’s about it… All you’ll need is to slap in these 3 lines of CSS to perfectly center anything and everything!

Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!