Top 3 Ways to Center a DIV with CSS 🚀

Archit Sharma - Jul 28 '22 - - Dev Community

In this blog will go over three approaches of centering a div.

The most difficult thing a web developer will ever have to accomplish is use CSS to center a div both horizontally and vertically.

Table of Contents

  1. Classic approach
  2. Flexbox approach
  3. Grid Layout center div

1. Classic approach

Classic approach
There are hundreds of methods to do the task, but the traditional method is to use absolute positioning, then move it down and to the right by 50% by using the top and left properties, and then move it back the other way by translating it 50%. Until flexbox came along, this perplexing hack was the gold standard.

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

2. Flexbox approach

Flexbox approach
The Flexible Box Layout Module facilitates the creation of flexible responsive layout structures without the use of float or positioning.
We can use Flexbox to turn the parent div into a flexible column or row, then align and justify the children in the center.

.flex {
    display: flex;
    align-items: center;
    justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

3. Grid Layout

Grid layout
Flexbox is a nice choice, but we can now accomplish it with even less lines of code by using Grid layout to detect the parent div as a grid and then instruct it to center the components.

.grid {
    display: grid;
    place-items: center;
}
Enter fullscreen mode Exit fullscreen mode
Thank you for reading this article; do follow me for more.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player