CSS Flexbox most easy center vertical and horizontal

โ€” 3 minute read

permalink

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 permalink

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 permalink

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

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

CSS Flexbox center multiple items permalink

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! permalink

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