CSS Flexbox most easy center vertical and horizontal
permalinkEver needed to just center an element completely? Before flex
this was almost impossible and we had some crazy hacks for this... Nowadays flex
makes it only 3 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 very basic, but yet so powerful option to center elements.
Note: I also wrote a article on how to center using CSS Grid.
CSS Flexbox horizontal center permalink
To center vertical we use the justify-content: center;
option.
.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
For the horizontal center we can use align-items: center;
option.
.container {
display: flex;
align-items: center;
}
CSS Flexbox center multiple items permalink
Ofcourse 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