CSS Grid: Is It Possible To Apply Color To Grid Gaps?
Answer :
Sadly, there is currently no way in the CSS Grid spec to style grid-gap
. I came up with a solution that works well though that involves just html and css: show border grid lines only between elements
For instance: if one has a 5x5 grid of squares, is the only way to get colored grid lines to fill the grid with 25 elements and apply borders to those same elements?
You could do that, but grid borders do not collapse the same way that table borders can with the border-collapse
property, and unlike grid gaps they'll be applied to the perimeter of your grid along with the inner borders, which may not be desired. Plus, if you have a grid-gap
declaration, the gaps will separate your grid item borders much like border-collapse: separate
does with table borders.
grid-gap
is the idiomatic approach for spacing grid items, but it's not ideal since grid gaps are just that: empty space, not physical boxes. To that end, the only way to color these gaps is to apply a background color to the grid container.
Instead to use the solution above I recommend to use border
with pseudo-classes because if you have an irregular amount of "table cells" you will end up with an ugly color filled cell at the end of the "table".
.wrapper {
display: grid;
grid-template-columns: repeat(2, auto);
/* with flexbox:
display: flex;
flex-wrap: wrap;
*/
}
/* Add border bottom to all items */
.item {
padding: 10px;
border-bottom: 1px solid black;
/* with flexbox:
width: calc(50% - 21px);
*/
}
/* Remove border bottom from last item & from second last if its odd */
.item:last-child, .item:nth-last-child(2):nth-child(odd) {
border-bottom: none;
}
/* Add right border to every second item */
.item:nth-child(odd) {
border-right: 1px solid black;
}
<div class="wrapper">
<div class="item">BOX 1</div>
<div class="item">BOX 2</div>
<div class="item">BOX 3</div>
<div class="item">BOX 4</div>
<div class="item">BOX 5</div>
</div>
Comments
Post a Comment