CSS: Centering a Div or elements

I have being learning CSS and practicing the things I have learnt the main thing that I am slightly confused about is centring elements or div’s containing elements:

So for a div to be a parent we would set the div position to relative;

and the elements inside the div would be absolute;

But what’s the best way to center a div and center the elements inside of it, is it best to use margins or just use left:100px for example.

thanks
bnmz41998

Setting elements to position: absolute should be the last option of choice because it is tricky to make that responsive. There are several options to center elements:

Inline elements like spans

text-align: center;

Block elements like divs

for parent elements:

margin: auto; // for the parent

for child elements:

display: flex; 
justify-content: center;
1 Like

I would add if you want to center both vertically and horizontally, you’d also want to add align-items:

#parentContainer {
  display: flex;
  justify-content: center;
  align-items: center;
}

The least code to center a div within a parent element award, though, belongs to grid:

#parentContainer {
  display: grid;
  place-items: center;
}