17
Clearing Rows with CSS Grid
Today I completed a fun little challenge using CSS Grid.
The goal was to update a layout that relied on container elements and flexbox.
<div class="cards">
<pfe-card id="a-1">...</pfe-card>
<pfe-card id="a-2">...</pfe-card>
<pfe-card id="a-3">...</pfe-card>
<pfe-card id="a-4">...</pfe-card>
</div>
<div class="cards">
<pfe-card id="b-1">...</pfe-card>
<pfe-card id="b-2">...</pfe-card>
<pfe-card id="b-3">...</pfe-card>
<pfe-card id="b-4">...</pfe-card>
</div>
.cards {
display: flex;
flex-flow: row wrap;
}
.cards > * {
margin-bottom: 15px;
margin-right: 15px;
min-width: 200px;
width: calc(25% - 32px);
}
My first step was to remove the container elements and 'lift up' the flex properties into the grid container
<pfe-card id="a-1">...</pfe-card>
<pfe-card id="a-2">...</pfe-card>
<pfe-card id="a-3">...</pfe-card>
<pfe-card id="a-4">...</pfe-card>
<pfe-card id="b-1">...</pfe-card>
<pfe-card id="b-2">...</pfe-card>
<pfe-card id="b-3">...</pfe-card>
<pfe-card id="b-4">...</pfe-card>
:host {
display: grid;
grid-template-columns: repeat(
auto-fill,
minmax(
200px,
calc(25% - 32px)));
grid-auto-rows: max-content;
gap: 15px;
}
This did most of the job on its own, but there was one issue: in the original layout, card b-1
appeared in a new 'row' below the first set of cards. How could I emulate this 'row-clearing' behaviour? Using grid-column
, I specified the position of the first card in the second set:
#b-1 {
grid-column: 1/2;
}
Now, that one specific card 'resets' it's whole row, replicating the original behaviour, but with fewer non-semantic elements, and less CSS.
nice
17