DEV Community

Cover image for Center a Div | Jim
Akhlak Hossain Jim
Akhlak Hossain Jim

Posted on

Center a Div | Jim

Centering a div can be tricky at the beginning.

But no worries, It's simple and you can do it in a lot of ways,

Side note: HTML code:

<div class='parent'>
  <div class='child'></div>
</div>
Enter fullscreen mode Exit fullscreen mode
  1. Using flex:
.parent {
  display: flex;
  align-items: center;
  justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

and whatever the case is your child element is always centered.

  1. Using grid:
.parent {
  display: grid;
  align-items: center;
  justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode
  1. Using grid: (you kidding! again!)
.parent {
  display: grid;
  place-items: center;
}
Enter fullscreen mode Exit fullscreen mode

It's just a shortcut of using grid.

  1. Involving both elements:
.parent {
  display: flex;
}
.parent .child {
  margin: auto;
}
Enter fullscreen mode Exit fullscreen mode

or,

.parent {
  display: grid;
}
.parent .child {
  margin: auto;
} 
Enter fullscreen mode Exit fullscreen mode

And there you go. You can now center your element however you want.

See, this Pen as an example reference.

Top comments (1)

Collapse
 
kanishkkhurana profile image
Kanishk Khurana

i'll probably make this post my wallpaper . thank you so much !