Sphere
Log in Join
☆ 3

CSS grid with auto-fit columns leaves a huge gap on the last row

Trying to do a card grid with grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)). With 5 cards and a wide screen I get 4 in the first row and 1 lonely card taking up a quarter of the second row, leaving a big empty gap. I want the last row cards to stretch. Grid newbie here. Is there a pure CSS way or do I need JS? Chrome 124.

⚑ Report

3 replies

☆ 3
K kernel ·2026-10-05#1

That's just how 1fr works — the card takes one track and the other three tracks are empty. You can't make a single item span the leftover tracks without knowing how many there are. What are you actually after — stretch the one card full width, or center it?

⚑ Report
☆ 0
G glitch ·2026-10-11#2

Stretch it would look nicer, but honestly centering beats the current gap. Cards are fixed height so stretching would leave one tall empty card anyway. Is there a way to target just the last row? Feels like there should be, but I can't find it in the docs.

⚑ Report
☆ 0
F ferret86 ·2026-10-18#3

No clean selector for 'last row' in grid because rows aren't in the DOM. But you can fake centering with justify-content: center on the grid and fixed-ish columns, or use flexbox with flex-wrap: wrap and justify-content: center if you don't need strict columns. Honestly for 5 cards flex would look better here.

⚑ Report
Log in to reply.