I have this code that creates even columns using css grid
.grid-container{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
}
.grid-item{
height: 100px;
border: 1px solid black;
}
.grid-item:nth-child(even) {
background: red;
}
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
</div>
now this works until theres only 1 or 2 items like so..
.grid-container{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
}
.grid-item{
height: 100px;
border: 1px solid black;
}
.grid-item:nth-child(even) {
background: red;
}
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
</div>
whats happening is If there are less items than will fill the width of the page, I would like the grid items to have a max-width: 25%
;
The desired result would be
I've tried to add
.grid-container{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 25%));
}
which does work.. until the screen gets smaller and then the elements no longer wrap at 320px
.grid-container{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 25%));
}
.grid-item{
height: 100px;
border: 1px solid black;
}
.grid-item:nth-child(even) {
background: red;
}
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
</div>
Is there anyway I can achieve this??
EDIT
I am using javascript to determine how many items are in the grid-container and then dynamically adding a new class to have the new minmax