Top three ways to center a DIV with CSS

Black Lilly
2 min readApr 8, 2021

The most difficult thing a web developer ever has to do is center a div both horizontally and vertically with CSS.

There are hundreds of ways to get the job done. But the classic approach is use absolute positioning then move it down and to the right by 50 percentage by using the top and left properties. Then move it back the direction by translating it 50% .

Center a DIV using position

Above confusing hack was the gold standard until flexbox came around where we can make the parent DIV a flexible column or row, then align and justify the children in a center.

Center a DIV using flex.

“Display : flex;” , That’s a great option but today we can do it with even fewer lines of code using grid layout.

Just to find the parent DIV as a grid and then tell it to place the items in the center . Yes it’s just that simple.

Center a DIV using grid option.

Hey there !. If you find it useful, please share . Thank you !

--

--

Black Lilly
0 Followers

nature lover, have stuff in programming and the farmer