Auto margin in CSS Grid items

webdev

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, center.

Now, 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.

Using margin:auto will give the same effect as using align-self and justify-self with value, center, for each, in grid items.

<head>
<style>
#grid{
display: grid;
grid-template-areas: "one two three"; /* more style */
}
.griditems:nth-of-type(1){ grid-area: one; }
.griditems:nth-of-type(2){ grid-area: two; }
.griditems:nth-of-type(3){ grid-area: three;}
.griditems{
margin: auto; /* more style */
}
</style>
</head>
<body>
<div id="grid">
<img src="foo.com/img-1.jpg" class="griditems">
<img src="foo.com/img-2.jpg" class="griditems">
<img src="foo.com/img-3.jpg" class="griditems">
</div>
</body>

Credit: Illustration used in the post header is by Adam Szary.

The Author

Web developer and writer. @rpsthecoder in Twitter.