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.

enter image description here

There can be 4 columns in a row if each column takes 4 wide (4 x 4 = 16).

enter image description here

And there can only be one column per row if each takes 16 wide.

enter image description here

Problem

When I'm shrinking the Grid, the column goes overflow.

enter image description here

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.

enter image description here

※ 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;
}

1 answer

  • answered 2022-05-06 12:19 Temani Afif

    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>

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum