Learn how to utilize the functional notation of nth-child by referring to the resources provided here and here. Experiment with the following settings:
justify-items: center;
for the grid itself
justify-self: start;
for every third grid item starting from the first one
justify-self: end;
for every third grid item starting from the third one
#grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 1em;
justify-items: center;
border: 2px solid cyan;
}
.gridItem {
border: 2px solid red;
height: 10rem;
}
/* for every 3rd item starting with the first one */
.gridItem:nth-child(3n+1) {
border: 2px solid yellow;
justify-self: start;
}
/* for every 3rd item starting with the third one */
.gridItem:nth-child(3n+3) {
border: 2px solid blue;
justify-self: end;
}
.gridItem img {
width: 100px;
}
<div id="grid">
<div id="1" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
<div id="2" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
<div id="3" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
<div id="4" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
<div id="5" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
</div>
If you're open to using auto
for column widths instead of 1fr
, consider implementing justify-content: space-between;
similar to flexbox. This approach offers a straightforward solution.
#grid {
display: grid;
grid-template-columns: auto auto auto;
gap: 1em;
justify-content: space-between;
border: 2px solid cyan;
}
.gridItem {
border: 2px solid red;
height: 10rem;
}
.gridItem img {
width: 100px;
}
<div id="grid">
<div id="1" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
<div id="2" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
<div id="3" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
<div id="4" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
<div id="5" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
</div>