Setting minimum and maximum number of columns using CSS Grid

Sumit Bagga picture Sumit Bagga · Sep 20, 2018 · Viewed 19.1k times · Source

I have 10 divs (64px x 64px) that I want to display in 5 columns maximum (for Large and Extra Large viewports) and 3 columns minimum (for small viewports like iPhone 7 etc).

I am trying to do this with CSS Grid but not able to do the minimum columns part (It goes to 2 columns even if there is space to fit 3 cols).

Max width for the grid container is 800px.

Here is the link for Codepen

Edit: If possible, I want to accomplish this only using CSS Grid i.e. without using Media Queries or Flexbox.

Answer

SantoshK picture SantoshK · Sep 20, 2018

you can get required output by using @media query used grid-template-columns: repeat(5, 1fr); for large device and grid-template-columns: repeat(3, 1fr); for small device

body {
  background-color: wheat;
}

.parent {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(5, 1fr);  
}

.child {
  height: 64px;
  width: 64px;
  background-color: brown;
}

@media(max-width:540px){
  .parent {
     grid-template-columns: repeat(3, 1fr);
  }
}
<body>
  <div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>
</body>