Profile Picture
Heru Hermawan
Open menu

CSS Flexbox to center vertical and horizontal

13/4/2022

––– views

CSS Flexbox to center vertical and horizontal

Have you ever needed to perfectly center an element? Before flex, this was nearly impossible, and we had to come up with some wild and crazy workarounds. With, flex, it's now simply three lines of CSS 😆.

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

That's it! Of course, this is a simple yet effective way to center elements.

Note: I also wrote an article on how to center using CSS Grid.

CSS Flexbox horizontal center

To center horizontally, we use the justify-content: center; option.

CSS
.container {
display: flex;
justify-content: center;
}

CSS Flexbox vertical center

To center vertically, we can use the align-items: center; option.

CSS
.container {
display: flex;
align-items: center;
}

CSS Flexbox center multiple items

We can, of course, do this with multiple items.

We can use flex-direction: column; or flex-direction: row; to specify which way the elements should flow when using multiple items.

CSS
.container {
display: flex;
flex-direction: row; /* horizontal axis */
flex-direction: column; /* vertical axis */
justify-content: center;
align-items: center;
}

To see the difference, take a look at this example: (scroll down)

That's it! Using CSS Flexbox, we can now center elements horizontally, vertically, or both. 🤗

Happy coding!

Thank you for reading 🙏. Feel free to share and/or react!


Article Reactions

👍
❤️
👏
🎉
💯

Share Article


More articles

If you enjoyed this article, you'll find these insightful too!

CSS Grid to center vertical and horizontal

CSS Grid to center vertical and horizontal

27/4/2022 Read

How to center an element vertical and horizontal using grid css.

Introduction to Networking - Terminologies

Introduction to Networking - Terminologies

9/5/2022 Read

A list of some common and basic networking terminologies.

Introduction to Networking - Interfaces and Protocols

Introduction to Networking - Interfaces and Protocols

16/5/2022 Read

A list of some common and basic networking interfaces and protocols.