Search code examples
htmlcsscss-grid

CSS Grid Template Columns Repeat No More Than X Times


I have a layout in which multiple items will be aligned in a grid. Let's use the following as an example:

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
}

.grid-item {
  display: block;
  width: 100%;
  background-color: purple;
  color: white;
  text-align: center;
  padding: 30px 5px;
}
<div class="grid-container">
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
</div>

In the above code, the grid will repeat 3 columns per row and each item will expand to 1/3 of the row width. The problem is that in a responsive situation, the grid will always repeat 3 columns.

If I change the repeat value to auto-fit and adjust the column sizing to use minmax I can control how the page scales down and reduce the col width and count to some sane value. So adjusted code would look something like this:

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px,1fr));
  grid-gap: 20px;
}

.grid-item {
  display: block;
  width: 100%;
  background-color: teal;
  color: white;
  text-align: center;
  padding: 30px 5px;
}
<div class="grid-container">
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
  <div class="grid-item">Item</div>
</div>

This works well scaling down, but here is where I am having problems - I want to cap the number of cols at 3 when the page scales up. Ideally, I would like to use minmax in the repeat directive like this:

grid-template-columns: repeat( minmax(1, 3), minmax(300px, 1fr) );

but of course this doesn't work. How can I limit repeat to 3 columns while still maintaining my downscale settings with auto-fit?


Solution

  • if I understand correctly what you can do is set a media query for larger screens. Lets say you want to show a 3 column grid for screens over 992px you can use something like this

    @media only screen and (min-width: 992px){
      .grid-container{
        grid-template-columns: repeat(3, 1fr);
      }
    }
    

    Let me know if that helps you! check it here https://codepen.io/anon/pen/Krzbmz