I try to achieve a grid with a flexible amount of columns using grid-template-columns: repeat(auto-fill, minmax(Xpx, 1fr)); and have some cells span multiple columns using grid-column-end: span Y; as shown in the code snippet below. This works like a charm with large grid containers, the trouble starts when the container is below Y * Xpx (ignoring the grid gap) as then the grid-column-end: span Y enforces a minimum of Y columns even though the auto-fill would result in less columns due to the minimum column width constraint not being met. Hit the button to toggle a constraint on the grid container and see that when the container is constrained to 300px, then it still has 3 columns instead of only one, due to element K spanning 3 columns.
How can I configure cells to span multiple columns but in maximum the number of columns in the grid? I.e. element K should span 3 columns by default but only one (or two) if there are less columns in the grid.
Using media queries to reduce the col-span is not an option as the sizing should be dependent on the grid container width and not the viewport width. This is due to the grid being not the only thing on the page.
document.getElementById('constrain-grid-width').addEventListener('click', function (e) {
e.preventDefault();
const example = document.getElementById('grid-example')
if (example.style.width == '') {
example.style.width = '300px';
} else {
example.style.width = '';
}
})
.wrapper {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
background-color: #fff;
color: #444;
}
.box {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
}
.a {
grid-column: auto / span 2;
}
.k {
grid-column: auto / span 3;
}
.g {
grid-column: auto / span 2;
grid-row: auto / span 2;
}
<button id="constrain-grid-width">Toggle grid container width constraint to show problem</button>
<div class="wrapper" id="grid-example">
<div class="box a">A</div>
<div class="box b">B</div>
<div class="box c">C</div>
<div class="box d">D</div>
<div class="box e">E</div>
<div class="box f">F</div>
<div class="box g">G</div>
<div class="box h">H</div>
<div class="box i">I</div>
<div class="box j">J</div>
<div class="box k">K</div>
<div class="box l">L</div>
<div class="box m">M</div>
</div>
Example copied and adapted from https://gridbyexample.com/examples/code/example29.html