Search code examples
htmlcsssasscss-grid

Grid whose amount of columns should be between 1 and 3


On my website I have a grid which should have between 1 and 3 columns. I can easily make the amount of columns dynamic by using auto-fit:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min-content, 1fr));
  gap: 40px;
}

However the amount of columns can go above 3 which looks terrible on wider screens and I couldn't find a way to limit the amount of columns.
This is what it looks like with 5 columns (bad): bad image

I tried using max(3) instead ofauto-fit, but that just set the amount to 3, not making it dynamic.
What's something I can do to limit the amount of columns to 3?


Solution

  • Fixed it like this:

    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 40px;
    }
    @media only screen and (min-width: 1450px) {
      .grid {
        grid-template-columns: repeat(3, minmax(300px, 1fr));
      }
    }
    

    Thanks for the @media suggestion!