Nick Bull Blog

Nick Bull Blog

How to center horizontally and vertically using flexbox? (HTML/CSS)

How to center horizontally and vertically using flexbox? (HTML/CSS)

You have a problem

You want to center horizontally and vertically element or elements using flexbox CSS property.

Here's how to do it.

Solution

If you want to center element using flexbox use justify-content: center and align-items: center properties.

Example:

<div id="outer">
  <div>Center me</div>
</div>
#outer {
  display: flex;
  justify-content: center;
  align-items: center;
}

Result:

If you want to center elements in a row using flexbox use flex-direction: row and the same properties as above.

Example:

<div id="outer">
  <div>Center me 1</div>
  <div>Center me 2</div>
</div>
#outer {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

Result:

If you want to center elements in a column using flexbox use flex-direction: column and the same properties as above.

Example:

<div id="outer">
  <div>Center me 1</div>
  <div>Center me 2</div>
</div>
#outer {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

Result:

In the end...

Hope you found this solution to center elements using flexbox useful!

I share a lot of useful HTML, CSS, and JavaScript tips on Twitter, if you want to upgrade your skills don't forget to follow me (or just to say Hi).

And also, every week I send out a "3–2–1" newsletter with 3 tech news, 2 articles, and 1 piece of advice for you.

📌 Subscribe to my 3–2–1 newsletter! 📌

 
Share this