Adding Internal Borders To CSS Grid
24 April 2024
I was recently building out a grid of products and wanted to add internal borders to separate the items within. I’d tried adding a border to the individual grid items, but that results in a double border where they meet - not what I was going for in the design.
My requirements were to have a 1px border in between each of the grid items and that the borders respond appropriately when the grid rows and columns change - when the grid goes from three to two to one column based on the viewport width.
My first thought was “isn’t this something we can do with CSS grid already?” After a lot of searching, it seems not, at least based on the searches I did. My second thought was, “it shouldn’t be hard to achieve something like this in 2024” - and thankfully it’s not.
I found various overcomplicated solutions while searching, some using crazy :nth-child selectors and another making use of pseudo :before and :after elements. And then I found one on Codepen that was so simple, that it’s beautiful and ingenius.
Rather than try to over-engineer something, this solution leans into the gap property. Put a background colour on the grid container, create your borders by applying gap. It works every time no matter what viewport size or grid configuration because it’s simple and uses what the browser and CSS provide.
Want to get even fancier? You can apply different border widths to rows and columns by using the row and column gap properties individually.