How do I use HTML / CSS to have items span a grid if there are fewer items in the row than there are columns?

2 weeks ago 19
ARTICLE AD BOX

I'm trying to create a grid with three columns, but if there are fewer than three items in a given row, I want the items to span the width of the grid. I'm including a screenshot of my current layout, an edit showing what I would like, and snippets of my HTML and CSS:

Current Layout (Note: the title at the top is done with a separate grid than the one with pictures. If there is a better way to do this, any help would be appreciated.):

A grid layout showing a title bar at the top, three items in the first row, and two items in the second row. The second row has an empty space below the third item in the first row.

Desired Layout:

A grid layout showing a title bar at the top, three items in the first row, and two items in the second row. The second row has both of its items span the length of the grid despite having one fewer item than the row above.

HTML:

<div id="grid-title"><h3>Botanicals</h3></div> <div id="grid-body"> <div id="grid-item"> <img src="img/LEGO-cherry-blossoms-set.png" alt="LEGO Cherry Blossoms Set" style="width: 10vw"><br> <a href="https://rebrickable.com/sets/40725-1/cherry-blossoms/#parts">Cherry Blossoms</a> </div> <div id="grid-item"> <img src="img/LEGO-happy-plants-set.png" alt="LEGO Happy Plants Set" style="width: 10vw"><br> <a href="https://rebrickable.com/sets/10349-1/happy-plants/#parts">Happy Plants</a> </div> <div id="grid-item"> <img src="img/LEGO-lucky-bamboo-set.png" alt="LEGO Lucky Bamboo Set" style="width: 10vw"><br> <a href="https://rebrickable.com/sets/10344-1/lucky-bamboo/#parts">Lucky Bamboo</a> </div> <div id="grid-item"> <img src="img/LEGO-mini-orchid-set.png" alt="LEGO Mini Orchid Set" style="width: 10vw"><br> <a href="https://rebrickable.com/sets/10343-1/mini-orchid/#parts">Mini Orchid</a> </div> <div id="grid-item"> <img src="img/LEGO-sunflowers-set.png" alt="LEGO Sunflowers Set" style="width: 10vw"><br> <a href="https://rebrickable.com/sets/40524-1/sunflowers/#parts">Sunflowers</a> </div> </div>

CSS:

#grid-title{ display: grid; grid-template-columns: auto; border: 1px solid black; background-color: var(--navbarbg); text-align: center; } #grid-body{ display: grid; grid-template-columns: 1fr 1fr 1fr; text-align: center; } #grid-item{ justify-content: center; border: 1px solid black; }
Read Entire Article