我有这段代码可以使用CSS网格创建偶数列
.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>
现在这可以工作,直到只有1或2个项目为止。
.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>
发生的事情是,如果项目少于填充页面宽度的项目,我希望网格项目具有max-width: 25%
;
所需的结果将是
我尝试添加
.grid-container{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 25%));
}
它起作用..直到屏幕变小,然后元素不再缠绕在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>
反正我能做到吗?
编辑
我正在使用javascript确定网格容器中有多少个项目,然后动态添加一个新类以具有新的minmax