Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting minimum and maximum number of columns using CSS Grid

Tags:

html

css

css-grid

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

body {    background-color: wheat;  }    .parent {    display: grid;    grid-gap: 10px;    grid-template-columns: repeat(auto-fill, minmax(100px, 140px));    max-width: 800px;  }    .child {    height: 64px;    width: 64px;    background-color: brown;  }
<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>

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.

like image 287
Sumit Bagga Avatar asked Sep 20 '18 04:09

Sumit Bagga


People also ask

How do you specify the number of columns in a CSS Grid?

To specify the number of columns of the grid and the widths of each column, the CSS property grid-template-columns is used on the grid container. The number of width values determines the number of columns and each width value can be either in pixels( px ) or percentages(%).

How do I set grid column size?

Set the following on the grid container: grid-template-columns: auto 1fr; This sets the width of the first column to equal the width of the widest item in that column, and the width of the second column to get the remaining width of the grid.


1 Answers

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>
like image 70
SantoshK Avatar answered Sep 29 '22 10:09

SantoshK