Colouring CSS Grid lines
This past week I built a theme for a client that used a 12 column grid. The grid ran the entire length of the page and had 1px
wide grid lines separating each of the columns. Each row of the grid contained content, but not every column in a row was occupied.
My first port of call with anything CSS related is always the MDN web docs. I've used the grid-gap
property many times but I wanted to check to see if it accepted any values other than length/percentage (it doesn't). Then I checked the CSS properties related specifically to CSS Grid to see if there was a property that could do the trick but that I wasn't aware of (there isn't).
I needed to find another way. I found two.
Solution One: background-color
Whatever colour we want our grid lines to be (in this example: black), we set that colour as the background colour for the .grid
wrapper. Then, we apply a background colour to our .grid__item
's (in this example: white).
Finally, we add grid-gap: 1px
to put a small space between the grid columns.
There's one small problem with this solution: what if our site background isn't a solid colour, or uses an image instead? If we need our grid columns to be transparent, then we need a slightly different approach.
Solution Two: border-color
With the border approach, we apply border-left: 1px solid #000;
to .grid__item
. We don't need to apply a grid gap at all, because the border creates it. But we do need to remove the border from the first .grid__item
child otherwise we'll end up with one too many lines.
Both solutions work, but...
It would be nice if there was a way that CSS Grid could handle gap colour so that we don't have to add extra markup just to achieve the same effect.