Auto Grid Utility

Our auto-grid utility is constructed as follows:

.auto-grid {
display: grid;
grid-template-columns: repeat(var(--auto-grid-method, auto-fill), minmax(var(--auto-grid-min, 16rem), 1fr));
grid-gap: var(--auto-grid-gap, 1rem);
}

.auto-grid--fit {
--auto-grid-method: auto-fit;
}

Purpose

This utility allows developers to create a reusable responsive grid system that is fluid and can adapt across sizes. We have CSS variables to control certain parts of the grid.

auto-grid-method

Allows us to control whether columns fit the container, or whether they should fill the container. Options are auto-fill or auto-fit. You can read more about these options.

auto-grid-min

This is where we control how the columns are sized. By default, we set a min of 16rem and a max of 1fr which tells the grid to make sure each column is a minimum of 16rem, and a maximum of 1fr to fit the columns to the container. So when the columns can't fit the container, it'll begin to calculate and make sure the columns are a minimum 16rem. For example, this may give you the functionality depending on container width, where columns are 4 columns on desktop, 2 on tablet and then 1 on mobile. You can also do clever calculations using calc(), e.g:

--auto-grid-min: max(16rem, calc(50% - var(--auto-grid-min)))

This would make sure the minimum size is either 50% of the screen, or 16rem depending on which is bigger!

Example

<ul class="[ feature-grid ] [ auto-grid ]">
<li>Column 1</li>
<li>Column 2</li>
<li>Column 3</li>
</ul>
.feature-grid {
--auto-grid-gap: 2rem;
--auto-grid-min: 12rem;
}

This shows that we're not repeating the same lines of CSS over and over, display: grid etc. We're keeping CSS reusable, with clear separations of concerns.