Search code examples
csscss-grid

Minimum number of columns in grid


Keep in mind the value for the number of columns is dynamic, and can be set to any number between 2 and 5 columns.

I have two breakpoints for "tablet" and "desktop" and I want to have the number of columns for tablet be one less than desktop. However, I am trying to find a way to set a minimum number of columns for tablet as I don't want the number of columns to be 1 if "2" was selected.

I have the following (abbreviated) code so far:

.some-grid {
  --columns: 1;
  display: grid;
  grid-template-columns: repeat(var(--columns), 1fr);
}

@media (min-width: 751px) {
  .some-grid {
    /* This would output 1 column, but would like to set it to 2 minimum */
    --columns: calc(var(--columns-large) - 1);
  }
}

@media (min-width: 991px) {
  .some-grid {
    --columns-large: 2;
  }
}

Is this possible?


Solution

  • Use max()

    .some-grid {
      --columns: 1;
      display: grid;
      grid-template-columns: repeat(var(--columns), 1fr);
    }
    
    @media (min-width: 751px) {
      .some-grid {
        --columns: max(2,var(--columns-large) - 1);
      }
    }
    
    @media (min-width: 991px) {
      .some-grid {
        --columns-large: 2;
      }
    }
    
    /**/
    .some-grid {
      gap:5px;
    }
    .some-grid * {
      height:40px;
      background:red;
    }
    <div class="some-grid">
      <div></div>
      <div></div>
      <div></div>
    </div>