'Allows CSS Grid columns to be shorter than the Grid Gap to prevent overflow
I'm working on my grid system that allows up to 16 columns per row and each was divided with 1rem
gap.
There can be 4 columns in a row if each column takes 4 wide (4 x 4 = 16
).
And there can only be one column per row if each takes 16 wide.
Problem
When I'm shrinking the Grid, the column goes overflow.
The columns can shrink, but it couldn't be smaller than the Grid Gap.
1rem (Gap) * 16 (Columns per row) = 16rem
Hence the Grid cannot be shorter than 16rem
.
※ The black border indicates the Grid container.
Since it didn't happen with Flexbox, I wonder if there's any style allows the column to be shorter than the Grid Gap, so my Grid can be shorter than 16rem
?
Code
Grid
.ts-grid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(16, minmax(0, 1fr));
}
Columns
.ts-grid .column {
grid-column: auto / span 1;
}
Solution 1:[1]
Use min()
on the gap to decrease it when the container is small:
.grid {
display: grid;
gap: min(1rem, 5%);
grid-template-columns: repeat(16, minmax(0, 1fr));
border:1px solid;
}
.grid>div {
height:50px;
background:red;
}
.grid > div:only-child {
grid-column: span 16;
}
<div class="grid">
<div></div>
</div>
<div class="grid">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Temani Afif |