CSS grid and custom properties
When building client sites, it was a common request to adjust grid layouts based on content types. For example, if the content type was a blog article, we wanted to display three items per row and include a gap between the items equal to 1rem
. If the content type was a calendar event, we wanted two items per row and increase the gap to 2rem
.
To do this, we would typically create grid variants based on type – grid--article
, grid--event
, etc. This required us to know the content types before hand and increased the amount of CSS needed for our grid object.
Now we can make use of CSS grid and custom properties to create a flexible grid system. Below we create our grid object and create a custom property for grid-gap
and grid-items-per-row
and set their default values.
.o-grid {
--grid-gap: 1rem;
--grid-items-per-row: 3;
display: grid;
grid-gap: var(--grid-gap);
grid-template-columns: repeat((var(--grid-items-per-row)), 1fr);
}
.o-grid {
--grid-gap: 1rem;
--grid-items-per-row: 3;
display: grid;
grid-gap: var(--grid-gap);
grid-template-columns: repeat((var(--grid-items-per-row)), 1fr);
}
Now we can use of grid object with our defaults as seen below. With this we'd expect to see three items per row with a grid gap of 1rem
.
<div class="o-grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div class="o-grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
If we want to override the defaults, we can set our custom properties inline. Now we'd have a grid with two items per row and a grid gap of 2rem
.
<div class="o-grid" style="--grid-gap: 2rem; --grid-items-per-row: 2;">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div class="o-grid" style="--grid-gap: 2rem; --grid-items-per-row: 2;">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
Here's a demo on CodePen that you can play with.