Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading