I am trying to create a container with an unknown (dynamic) number of children. I want the container to have as many equally-sized columns as will fit without overflowing, with additional children wrapping to the next grid row. The columns should be sized based on the largest child (so that smaller children stretch, but the content of the children doesn't wrap or overflow).
Essentially, I want a way to use repeat(auto-fill, <some size>)
where <some size>
is automatically calculated to be the largest max-content
width of all grid items.
I am fully aware that repeat(auto-fill, ...)
doesn't work with "intrinsic" sizing. Using it with minmax(...)
where one of the two sizes is intrinsic (min-content
, max-content
, auto
, or an fr
unit) seems to just use the explicit size all the time. For example, repeat(auto-fill, minmax(20px, max-content))
just makes as many 20px-wide columns as will fit, completely ignoring max-content
, and causing items wider than 20px to overflow.
Is there any way to accomplish this without using JavaScript? I can imagine a solution that would use a MutationObserver
to continuously recalculate the size of the largest child and then use that for repeat(auto-fill, <size>)
, but I feel like this should be possible without scripts in 2025.
Here's example of what I'm trying to do (codepen):
.container {
width: 600px;
border: 1px solid red;
padding: 1em;
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.2em;
}
.item {
border: 2px solid blue;
padding: 0.5em;
min-width: max-content;
}
<div class="container">
<div class="item">
Short text
</div>
<div class="item">
Short-ish text
</div>
<div class="item">
Here is some longer text
</div>
<div class="item">
Some slightly longer text
</div>
<div class="item">
Some medium text
</div>
<div class="item">
Short text
</div>
<div class="item">
Short-ish text
</div>
<div class="item">
Here is some longer text
</div>
<div class="item">
Some slightly longer text
</div>
<div class="item">
Some medium text
</div>
</div>