Home > Mobile >  Allows CSS Grid columns to be shorter than the Grid Gap to prevent overflow
Allows CSS Grid columns to be shorter than the Grid Gap to prevent overflow

Time:05-06

I'm working on my 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;
}

CodePudding user response:

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 >
  <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></div>
  <div></div>
</div>

  • Related