在做商品列表的时候发现, 如果一行显示2个, 这种情况比较好处理:
.goodList {
display: flex; //显示到一行
flex-wrap: wrap; // 换行
justify-content: space-between; // 将主轴上进行贴靠两边布局
}
.goodsItems {
width: 230rpx; // 给定一个固定宽度
}
![](https://img.haomeiwen.com/i6449491/2751d29253ae2c1f.jpg)
但是要是每行显示3 个呢?
设置 justify-content: space-between; 换行的时候就会发现,如果第二行是两个, 就会将其布局到两边,没有按照顺序排列,这个就很头疼了,
现在有一个方法可以很好的解决当前的问题:
<body>
<section class="content">
<div class="item">元素</div>
<div class="item">元素</div>
<div class="item">元素</div>
<div class="item">元素</div>
<div class="item">元素</div>
<div class="item">元素</div>
<div class="item">元素</div>
</section>
</body>
<style>
.content {
width: 100%;
display: flex;
flex-wrap: wrap;
background-color: skyblue;
}
.item {
/* 1. 其中 10 为间隙的中和 */
width: calc((100% - 10px)/3);
height: 120px;
background-color: pink;
/* 2. 布局 上 0,右 5rpx,下 5rpx,左 0 */
margin: 0 5px 5px 0;
}
/* 3. 需要配合获取最右边的 Item, 去除其右边距 */
.item:nth-child(3n) {
/* 3. 去除第3n个的margin-right */
margin-right: 0;
}
</style>
注意:
1. css 要写在 item 中;
2. item 中不能设置 padding-left 和 padding-right,否则下面计算会不正确
3. 以每行三个 item 为例:
设置 item 的宽度: width: calc((100% - 10px)/3);
设置 item 的间隙: margin: 0 5px 5px 0;
需要注意的是: 10 = 5 * 2(为间隙个数), 且单位都为 px
4. 最后需要对每行的最后一个的 margin-right 进行清除;
`
网友评论