如何在下面的 flex 元素中设置每行的最大元素数?我想用动画每行制作 4 个元素:
.grid-items {
display: flex;
flex-wrap: wrap;
flex-direction: row;
}
.cell-item {
padding: 15px;
-webkit-transition: all 2s ease;
-moz-transition: all 2s ease;
-ms-transition: all 2s ease;
transition: all 2s ease;
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
}
.cell-item a {
background-color: #f2f2f2;
width: 100%;
height: 200px;
display: block;
}
.cell-item:hover {
-webkit-box-flex: 4;
-ms-flex-positive: 4;
flex-grow: 4;
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
transition: all 1s ease;
}
<div class="grid-items">
<div class="cell-item">
<a href="#">
</a>
</div>
<div class="cell-item">
<a href="#">
</a>
</div>
<div class="cell-item">
<a href="#">
</a>
</div>
<div class="cell-item">
<a href="#">
</a>
</div>
<div class="cell-item">
<a href="#">
</a>
</div>
<div class="cell-item">
<a href="#">
</a>
</div>
<div class="cell-item">
<a href="#">
</a>
</div>
<div class="cell-item">
<a href="#">
</a>
</div>
</div>
如果我向 flex 元素添加 25%,动画将不起作用:
.cell-item {
padding: 15px;
-webkit-transition: all 2s ease;
-moz-transition: all 2s ease;
-ms-transition: all 2s ease;
transition: all 2s ease;
-webkit-box-flex: 1 25%;
-ms-flex: 1 25%;
flex: 1 25%;
}
有什么想法吗?
最佳答案
据我所知,你有两种可能性。
1 - 添加间隔元素以强制分离。如果你的最大元素数是 12,那么你可以为此使用伪元素(因为你只有 2 个可用的伪元素,所以你最多可以设置 3 行)
.grid-items {
display: flex;
flex-wrap: wrap;
flex-direction: row;
}
.cell-item {
padding: 15px;
transition: all 2s ease;
flex: 1;
height: 200px;
background-color: silver;
margin: 10px;
}
.cell-item:hover {
flex-grow: 4;
}
.spacer {
flex-basis: 100%;
}
<div class="grid-items">
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="spacer"></div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
</div>
一个细微的变化是将间隔符放在 DOM 的后面,并将它们设置到它们所属的位置,顺序。这种方法的优点是如果您希望通过媒体查询更改每行的元素数
.grid-items {
display: flex;
flex-wrap: wrap;
flex-direction: row;
}
.cell-item {
padding: 15px;
transition: all 2s ease;
flex: 1;
height: 100px;
background-color: silver;
margin: 10px;
}
.cell-item:hover {
flex-grow: 4;
}
.spacer {
flex-basis: 100%;
order: 99;
}
.cell-item:nth-child(n+1):nth-child(-n+4) {
order: 1;
background-color: tomato;
}
.cell-item:nth-child(n+5):nth-child(-n+9) {
order: 3;
background-color: lightblue;
}
.spacer:nth-last-child(1) {
order: 2;
}
<div class="grid-items">
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="cell-item">
</div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
</div>
关于html - 如何使用动画限制每行的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49098196/