For an undefined number of columns, I don't believe it is possible with CSS Grid.
With regard to your comment:
I thought maybe it could be done with some magic and: grid-template-columns: repeat(auto-fill, minmax(???, ???))
That is the logical way to go, but it's a dead end.
The necessary rule would be something along these lines (using auto-fill
or auto-fit
):
grid-template-columns: repeat(auto-fill, minmax(auto, auto))
grid-template-columns: repeat(auto-fill, minmax(auto, max-content))
grid-template-columns: repeat(auto-fill, auto)
There are other possible variations using min-content
and fit-content()
.
Alas, these cannot work because the repeat()
function, when used with automatic repetitions, must contain at least one fixed length.
7.2.2.1. Syntax of
repeat()
Automatic repetitions (auto-fill
or auto-fit
) cannot be combined
with intrinsic or flexible sizes.
An intrinsic sizing function is min-content
, max-content
, auto
, fit-content()
.
A flexible sizing function is <flex>
(fr
).
The closest you can get with CSS Grid would be with grid-template-columns: auto
, an inline-level grid, and a defined number of columns. I'll post this solution for general info.
ul {
display: inline-grid;
grid-template-columns: repeat(4, auto);
grid-gap: 1px;
}
li {
background-color: white;
}
ul {
background-color: black;
border: 1px solid black;
list-style: none;
padding: 0;
font-size: 1.5rem;
}
<ul>
<li>1</li>
<li>1</li>
<li>22</li>
<li>1</li>
<li>1</li>
<li>333</li>
<li>1</li>
<li>1</li>
<li>4444</li>
<li>1</li>
<li>1</li>
<li>1</li><!-- added for demo -->
</ul>
Here's a separate issue that may arise when building a table with Grid Layout: