CSS grid, setting maximum span

Is there a way to set a max value for CSS grid-column: span such that it takes up n-columns maximum or spans across all available columns if there are fewer than that? If I use span in a grid with auto-fill it'll forces additional columns even when there isn't space for any and makes them look weird.
5 Replies
Wolle
Wolleβ€’9mo ago
Maybe min()/max()/minmax() can help you? If you use it with fr as max it won't add new columns.
MarkBoots
MarkBootsβ€’9mo ago
Mike Herchel
CSS-Tricks
An Auto-Filling CSS Grid With Max Columns of a Minimum Size | CSS-T...
Within Drupal 10 core, we’re implementing a new auto-filling CSS Grid technique that I think is cool enough to share with the world.
cirilla
cirillaβ€’9mo ago
Not the max columns there but like, if I put span 3 on something it'll force the grid to have 3 columns and it'll have zero width for the ones that don't naturally fit, is there some way to do it such that I can say "take up 3 columns at maximum otherwise span across however many there are"
<div class="container">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner long"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>

<style>
.container {
padding: 2rem;
background-color: yellow;
height: 5rem;

display: grid;
grid-template-columns: repeat(auto-fill, minmax(40rem, 1fr));
gap: 1rem;
}

.inner {
background-color: blue;
}

.inner.long {
grid-column: span 5;
}
</style>
<div class="container">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner long"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>

<style>
.container {
padding: 2rem;
background-color: yellow;
height: 5rem;

display: grid;
grid-template-columns: repeat(auto-fill, minmax(40rem, 1fr));
gap: 1rem;
}

.inner {
background-color: blue;
}

.inner.long {
grid-column: span 5;
}
</style>
Wolle
Wolleβ€’9mo ago
You can use column-start/end with negative numbers to count from the right side. But if I understand you correctly, you will probably need media queries or JS for that.
Kevin Powell
Kevin Powellβ€’9mo ago
That would be nice, but no, we don't have a way to do that. You could probably do some craziness with :nth-child and use the ~ combinator to come up with a solution, but it would involve manually having to figure out every possible combination based on it's location in the grid and how many siblings follow it, which sounds like an absolute nightmare πŸ˜†. JS is the way for this, if you really need it.