DEV Community

Cover image for Top 3 Ways to Center a DIV with CSS πŸš€
Archit Sharma
Archit Sharma

Posted on

Top 3 Ways to Center a DIV with CSS πŸš€

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.

Top comments (6)

Collapse
 
andrewbaisden profile image
Andrew Baisden

One of the most googled search terms by developers πŸ˜‚

Collapse
 
iarchitsharma profile image
Archit Sharma

This is why it deserves its own blog.πŸ˜‚

Collapse
 
firozansari profile image
Firoz Ansari • Edited

And I thought classic approach was:

.center {
  margin: 0 auto;
  width: 200px;
  border: 1px solid #ccc;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
iarchitsharma profile image
Archit Sharma

Nop, that's not the classic approach

Collapse
 
mjcoder profile image
Mohammad Javed

Approach 1 and 2 are the ones that I use the most. πŸ‘

Collapse
 
iarchitsharma profile image
Archit Sharma

Yes, I am aware that the first two ways are used by the majority of people😁