Centering a Div

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 we are going to see three ways to do it.

The Classic Approach: (absolute positioning)

The classic approach is to use absolute positioning then move it down into the right by 50% by the top and leftproperties then move it back the other direction by translating it 50%. This confusing hack was the gold standard.

.wrapper {

   position: absolute;

   top: 50% ;

   left: 50% ;

   transform: translate (-50%, -50%);

}

Flex Box:

When the flex box came around 2009, everything changed when we finally had less confusing steps to do. We can make the parent div a flexible column or row with the flex-directionproperty and then align and justify the children withalign-items and justify-center.

.wrapper {

   display: flex;

   align-items: center;

   justify-content: center;

}

CSS Grids:

If you wanted to do much simpler with even fewer lines using CSS Grid. We declare the parent div as div and then tell it to place the items in the center with place-items.

.wrapper {

   display: grid;

   place-items: center;

}