This content originally appeared on Go Make Things and was authored by Go Make Things
Today, I wanted to share a fun little snippet of CSS I learned from my friend Stephanie Eckles awesome SmolCSS website.
Let’s imagine you’ve got a bunch of content (maybe some photos or a list or Pokemon characters or something like that), and you want to display them in a grid. The number of items can vary from time to time, as can the width and height of each item.
As a result, you can’t commit to any sort of specific CSS Grid layout…
<div class="grid-flex">
<div>1</div>
<div>2345</div>
<div>fkufdafda</div>
<div>23fff9</div>
<div>2okjfda</div>
<div>123</div>
<div>09</div>
<div>fhfd8fda</div>
<div>1ljk</div>
<div>198u98hj<br>jkf</div>
<div>a</div>
</div>
A lot of folks reach for Flexbox with flex-wrap: wrap
for this.
.grid-flex {
display: flex;
gap: 1rem;
flex-wrap: wrap;
}
But it also highlights some of the differences between Flexbox and CSS Grid.
Flexbox automatically adjusts the container size based on the size of the content inside it. CSS Grid defines a container, and then fits the content inside it.
As a result of these differences, using Flexbox means the items don’t always line up with each other. There are ways are it using flex-shrink
, flex-grow
, and flex-basis
, but in my opinion, CSS Grid provides a much easier way to handle this.
Here’s an alternative approach using Stephanie’s snippet…
.grid-flex {
display: grid;
gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(min(var(--min-column-size, 15ch), 100%), 1fr));
}
As you can see, the content automatically wraps as well.
But unlike with Flexbox, each item has the same width and lines up on a grid.
The magic with this one is in the grid-template-columns
property and the repeat()
function. The minmax()
function defines the minimum and maximum size of each item.
The min()
function defines the minimum size to use from a set of values, with 15ch
as the smallest. The 100%
value prevents overflow on narrow viewports.
You’ll also notice there’s a --min-column-size
CSS variable.
If you define this on the HTML, it will override 15ch
so you can customize the minimum width.
<div class="grid-flex" style="--min-column-size: 10ch">
<!-- ... -->
</div>
I love this handy little snippet, and find myself using it more and more on client projects. Thanks Stephanie!
Like this? A Lean Web Club membership is the best way to support my work and help me create more free content.
This content originally appeared on Go Make Things and was authored by Go Make Things

Go Make Things | Sciencx (2025-05-01T14:30:00+00:00) Automatically wrapping CSS Grid. Retrieved from https://www.scien.cx/2025/05/01/automatically-wrapping-css-grid/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.