DEV Community

Cover image for How to Center a div Horizontally and Vertically
Amrin
Amrin

Posted on • Updated on • Originally published at coderamrin.hashnode.dev

How to Center a div Horizontally and Vertically

Centering a div is a crucial skill for a web developer. So, today I’ll share 3 ways to center a div horizontally and vertically.

Let’s get started.

If you prefer video then check it out here:

Note: to center a div with flexbox or grid you need to add flexbox or grid to the parent of that div.

#1. Using Flexbox

You can center a div horizontally and vertically with Flex box, with just 4 lines of code.

div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

#2. Using Grid

Centering a div with grid is much more easier than with flexbox.

div { 
  display: grid;
  place-items: center;
  height: 100vh; 
}
Enter fullscreen mode Exit fullscreen mode

#3. Using Position Absolute:

You can center a div with CSS positionning too.

div {
  position: absolute;
  top: 50%;
  left: 50%; 
  transform: translate(-50%, -50%);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

That’s it for today.

If you enjoyed reading this article, I think you’ll also enjoy my newsletter where I share my articles and videos, and other useful resources

Subscribe Now!

Also you can connect with me on Twitter at @coderamrin

Top comments (4)

Collapse
 
unclecheap profile image
UncleCHEAP

Let's not forget yet a 4th way. No need for "positioning."

.parent {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.child {
    display: inline-block;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
coderamrin profile image
Amrin

thanks for sharing

Collapse
 
vladi160 profile image
vladi160

Use min-height, instead of height

Collapse
 
coderamrin profile image
Amrin

thanks for sharing Vladi