Filling in the last row of a responsive grid | Tim Wilson

Filling in the last row of a responsive grid | Tim Wilson

Until we have widespread support for gap decorations , the easy trick for having borders between grid cells in CSS is giving the grid a 1px gap, setting the container's background color to the desired border color, and setting the cells' background colors to the desired background color:

As long as you don't need some other background to show through, this is really handy and saves you from crazy :nth selectors or a bunch of extra logic. The tradeoff is some extra complexity when you don't have the right number of items to fully fill the grid.

The math for figuring out how many empty cells to fill in is pretty simple.

You can find the total number of rows needed to fit all of the items with ceil(items / cols) . Then, multiply by the columns per row, and subtract the number of items that are already filled: ceil(items / cols) * cols - items .

In JSX, that would look something like this:

Things get a little ugly when the number of columns isn't fixed, such as in a container like this:

We could put together a bunch of extra math and logic to give each filler cell the appropriate breakpoint classes, but that would be a lot of work and pretty tricky to understand. Instead, we can keep it simple by just using separate filler cells for each breakpoint:

This does create a few more elements than absolutely necessary, but it's the cleanest solution I've found so far.

Here's the GridFiller component:

If you want a single filler cell to span the remaining columns without the extra borders in-between filler cells, you can take a similar approach:

There are a few other ways to attack this, but they lose on my criteria of avoiding custom CSS (apart from arbitrary Tailwind classes) and keeping the components simple.

For now, this does the trick. I can't wait to delete it.

Recommended articles