Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Three lines of CSS to center anything horizontally and vertically

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!

If you’re a visual learner, there’s a video that you can check out.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?