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 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 ๐Ÿ“–

Modifying an SVG path with CSS

10 Dec, 2022 ยท 2 min read

Modifying an SVG path with CSS

Animate an SVG path with CSS

9 Dec, 2022 ยท 2 min read

Animate an SVG path with CSS

Join 2097 devs and subscribe to my newsletter