8 ways to center content with CSS

No more searching “how to center a div”

Mujtaba Murtaza
2 min readDec 4, 2022

Hi (read Hello) World, welcome to my first Medium Blog! There’s 8 ways to center content in CSS (as far as I know). And if you’ve seen my post on Instagram then you probably already know the first 5. Enjoy!

If you don’t wanna read the the thing below (because I don’t), then you can check out the below CodePen with all the ways you can center content! You’re welcome xoxo.

CodePen — the CSS centering holy grail

1. Table 🏓

Although a bit ol’ fashioned, but you do you mate.

2. Absolute 🧽

If you’re absolutely comfortable (pun intended) using the absolute positioning then I won’t stop you.

3. Flex 💪

Probably the most popular and easiest way of centering anything nowadays. I can safely admit that I use it for aligning paragraphs when I could’ve used text-align: center instead.

Flexbox can be slightly confusing if you don’t know what you’re doing (frankly I don’t either). Basically justify-content spans across the x-axis and align-items across the y-axis. If you set flex-direction to column then, the axes would be reversed.

This is not a flexbox blog so I can do a detailed one on this some day (lemme know in the comments if you want one)

4. Grid 📐

The modern way of doing things. Perfect for you if you’re an overachiever.

5. Flex/Grid + Margin auto 💣

If you’re feeling different today then this is it.

6. Text align ✍️

Yeah. It’s really that easy. But also feels illegal since this is text alignment specific (I’ve committed this crime shamelessly).

7. Paddings 🚀

If you have no fixed height and want to center vertically, this is probably the easiest way to do this.

8. Text align + Paddings 💥

It’s funny but cute and fast. You can use paddings to your advantage (provided you have no fixed height) and center something super quick.

Now, some of the methods I’ve shown above were either centered horizontally or vertically or both. It ultimately depends what you’re trying to build so I’m just showing different ways of doing the same thing.

Love,
@mujs.dev

--

--

Mujtaba Murtaza

Designer, Sr. UX Engineer, Philanthropist, Gamer, Making your life easier-er