I want a grid layout with any number of grid items, and when a grid item is filled, it automatically creates a new row, kind of like:
#grid { display: grid; width: 256px; border: 1px solid black; grid-gap: 12px; grid-template-columns: repeat(auto-fit, minmax(75px, 1fr)); } #grid span { background-color: lightgray; }
<div id=grid> <span>content 1</span> <span>content 2</span> <span>content 3</span> <span>content 4</span> <span>content 5</span> <span>content 6</span> <span>content 7</span> <span>content 8</span> <span>content 9</span> <span>content 10</span> </div>
The problem is that I don't want to hardcode 75px
. Is there a way to set this value to the "content width of the widest grid item"?
I tried changing 75px
to min-content
, which seems to work per spec, but the dev tools say this is invalid CSS. I've also tried setting just grid-auto-columns: min-content
instead of grid-template-columns
, which seems to set the width correctly but takes up A whole row.
The short answer is no. But it's a great question, and I think it's a common use case that really should be supported.
You will be in Grid template columns. Auto-repeat The relevant part of is
where fixed size is
Other bits are
This means that when using
minmax()
to automatically generate columns ingrid-template-columns
, your minimum or maximum value needs to be Fixed length or percentage. You can usemax-content
as the first value in a minmax expression, but only if you then use a fixed length or a percentage as the second value in the expression. Very annoying, isn't it? I wish I understood why this limitation exists.Can we solve this problem? Is this example closer to what you want?