Subscribe

CSS Flexbox most easy center vertical and horizontal

✍️

How to center a element vertical and horizontal using flexbox css

6 Apr, 2020 Β· 2 min read

Ever needed just to center an element entirely? This was almost impossible before flex, and we had some crazy hacks for this... Nowadays, flex makes it only three lines of CSS

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

Demo:

See the Pen CSS Flex most easy center vertical and horizontal by Chris Bongers (@rebelchris) on CodePen.

Simple as that! Of course, this is a fundamental yet powerful option to center elements.

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

CSS Flexbox horizontal center

We use the justify-content: center; option to center vertically.

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

See the Pen CSS Flex most easy center vertical by Chris Bongers (@rebelchris) on CodePen.

CSS Flexbox vertical center

We can use the align-items: center; option for the horizontal center.

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

CSS Flexbox center multiple items

Of course, we can do this with multiple items.

When using multiple items, we can use flex-direction: column; or flex-direction: row; to define which way the elements should flow.

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

See this example to see the difference: (scroll down)

See the Pen CSS Flex direction by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

CSS Logos: Figma logo

29 Mar, 2022 Β· 3 min read

CSS Logos: Figma logo

CSS art sucks

28 Mar, 2022 Β· 3 min read

CSS art sucks

Join 1371 devs and subscribe to my newsletter