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.
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(%).
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With