How to Center in CSS using Flexbox
2 min readDec 30, 2021

I don’t know about you guys, but centering in CSS has always been confusing to me. The main reason for this confusion is that the Display property in CSS has many options and they all work differently for different use-cases.
HTML Code for the above example

- We have 2 main divs with classes vertical & horizontal
- Each div has 3 labels and we will align them accordingly
Flexbox to the Rescue
- Flexbox is a layout model that is flexible, responsive & works on 2 axis
- There are 2 properties available to align on the 2 axis
~ justify-content property is for aligning on main axis
~ align-items property is for aligning on cross axis
Centering
Step 1
- Set display property to flex
Step 2
- Set flex-direction property to column for vertical div
- Set flex-direction property to row for horizontal div
- flex-direction property has 4 choices
~ row (left → right)
~ row-reverse (right → left)
~ column (top → bottom)
~ column-reverse (bottom → top)
Step 3
- Set align-items property to center for vertical div
- Set justify-content property to center for horizontal div

Complete HTML & CSS Code


Source Code : https://github.com/pandyama/css-flexbox-center