Let's imagine that you're using CSS Grid to create a magazine layout, with 1 large featured story and two smaller stories below:
Code Playground
CSS
HTML
Result
Right as you're ready to ship it, the lead designer pings you on Slack: “Hi Mahendra
— Hate to do this to you, but the design just got updated”.
Here's the new design:
Specifically, design wants us to add hot pink borders in-between each article, to add a bit of cosmetic panache.
If you'd like, you can spend a few minutes tinkering with this challenge. The hot-pink color has been provided in a CSS variable, --hot-pink.
Code Playground
CSS
HTML
Result
It's a tricky problem because there isn't any way to make the grid lines visible — even if we could, it wouldn't be exactly what we want, since some children span multiple rows/columns.
We can solve this using background colors though!
Here's the approach we'll take:
The grid children are given a background color that matches the page's background. The grid container is given a hot-pink background, but it only shows in the small spaces between and around the grid children.
Here's the code:
Code Playground
Result
Inset borders
The approach above was suggested by Discord user RebeccaB, and in general it's a way better approach than the one I originally used!
The only issue with this approach is that it's a little bit less flexible. For example, it won't work if we want our inner borders to be "inset", not reaching the edge of the container:
RebeccaB's background-color approach won't work here, since the borders aren't contiguous!
Here's how we can solve this new problem:
We'll add a large amount of padding to the overall container, since no border reaches the edge
We'll selectively add borders to specific grid children. For example, that first featured story will have a border along its bottom edge.
We'll use padding to increase the distance between borders, making sure that we apply padding "proportionally".
Here's what that looks like in code:
Code Playground
Result
story:nth-of-type(2n) selects the "extra-terrestrial" story, and any other stories that would fall into the first column (after the featured story). We give it 24px of right padding, and a border.
The stories in the second column are selected with story:nth-of-type(2n + 3), and they're given a symmetrical amount of left padding, so that both columns are equidistant from the border.
This approach feels a bit like solving a puzzle; we need to find a strategy for placing borders/padding around individual children that creates the illusion of an inner grid border.
In most cases, it's better to go with the simpler background-color approach, described earlier in this lesson. But when we need an extra amount of precision, this approach can provide much more flexibility.