Css grid centering the grid items

When I have a grid container wrapping 8 image elements and I have the container set as repeat(4,1fr) why doesn’t it center the images within their spacing?

Easy fix is adding some margin-left like I did but i don’t want to do that.

What’s the easy solution here to center the images within their square?

Thanks, cant think of the solution right now for some reason…

hi @Dobs

have you tried the display: block; margin: auto;.

im not sure how you structure the html.

<div class="grid">
  <img src=" ">
  <img src=" ">
</div>
.grid { display: grid; grid-template-columns: repeat(4, 1fr); }
.grid img { display: block; margin: auto; max-width: 100%; }

You have four grid columns, so the space is divided into four.

Each of the columns has an image in, but the image is not going to be the width of the grid ÷ 4.

Normally you want to set images to be width: 100%, height: auto so that they fill their containers

Note that if you’ve set a specific height for the rows, that’s not going to fix it – you may need to use the object-fit property to set how the image fits its container

1 Like