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
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%);
}
2. 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;
}
3. 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;
}
Thank you for reading this article; do follow me for more.
Top comments (6)
One of the most googled search terms by developers π
This is why it deserves its own blog.π
And I thought classic approach was:
Nop, that's not the classic approach
Approach 1 and 2 are the ones that I use the most. π
Yes, I am aware that the first two ways are used by the majority of peopleπ