How to Center in CSS using Flexbox

Meet Pandya
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

Only the body of the html code
  • 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
CSS code only for the 2 main divs

Complete HTML & CSS Code

Complete HTML Code
Complete CSS Code

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response