Using auto margin to center an item in both the horizontal and vertical axes is tricky — unless that item is a grid item.
We already have alignment properties exclusive for CSS layout models (including CSS Grid). To align a grid item in its grid area we can use
align-self (vertical alignment) and
justify-self (horizontal alignment).
And to center a grid item we give both of those properties the value,
margin: auto is something we often use on elements to center them horizontally in their containers.
The centering doesn’t work in vertical axis, till — beside the
margin:auto, we also give the elements
position:absolute; left:0; right:0; top:0; bottom:0;
But with grid items, we don’t need to give them absolute positioning,
margin:auto alone is enough to center the items in both the axes.
margin:auto will give the same effect as using
justify-self with value,
center, for each, in grid items.
Credit: Illustration used in the post header is by Adam Szary.