我想知道是否有办法每行有 4 个项目,但没有带有 <4 items to stretch to fill the space.
的行.item-container {
display: inline-flex;
flex-wrap: wrap;
flex-direction: row;
}
.item {
display: flex;
flex: 1 0 calc(25% - 40px);
color: black;
background-color: rgba(250, 250, 210);
flex-direction: column;
padding: 10px;
margin: 10px;
border-radius: 20px;
}
/* If there are 4 items it works well, but if there is 1-3 items they stretch to fill the space and look off. */
grid
布局非常适合这个。
以下属性:
grid-template-columns: repeat( auto-fill, minmax(calc(25% - 40px), 1fr) )
创建一个新列,只要它适合布局即可。列的最小尺寸必须是
minmax()
中指定的第一个值,最大值为 1fr
,仅相当于 1 列。
恕我直言,应该使用
calc(25% - 40px)
以外的另一个值,因为它现在正在计算相对于列的值。
/* demo purpose */
body {
display: flex;
flex-direction: column;
}
.item-container {
display: grid;
grid-template-columns: repeat( auto-fill, minmax(100px, 1fr) );
max-width: 400px;
}
.item {
display: flex;
color: black;
background-color: rgba(250, 250, 210);
flex-direction: column;
padding: 10px;
margin: 10px;
border-radius: 20px;
}
<div class="item-container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="item-container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="item-container">
<div class="item"></div>
<div class="item"></div>
</div>
<div class="item-container">
<div class="item"></div>
</div>