1、前言
flex布局时经常遇到这样一个问题,如下图,就是如何用flex布局平均分布,又可以换行然后最后一行如果不能铺满又可以左对齐呢呢?(ps:使用空的item元素填充这个方法就不说了…)
2、左对齐的那些方法
2.1 子元素item宽度固定即列数是固定的
2.1.1 使用 margin-right:auto
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| .container { display: flex; justify-content: space-between; flex-wrap: wrap; flex-direction: row; }
.list { flex: 0 0 calc(100vw / 4); height: 100px; background-color: skyblue; margin-top: 15px; }
.list:last-child { margin-right: auto; }
|
点击看使用margin-right:auto实现左对齐
2.1.2 手动计算子元素的 margin-right
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| .container { display: flex; flex-wrap: wrap; // 手动计算则无需使用 justify-content: space-between }
.list { flex: 0 0 24%; height: 100px; background-color: skyblue; margin-top: 15px; }
// 这个css选择器的意思是:当每行为4个时,选择每行的前三个 .list:not(:nth-child(4n)) { margin-right: calc(4% / 3); // 4% 是由上面的 24% * 4 得来,除以3 是因为每列显示4个产生了3段间距(最左边和最右边没有) }
|
点击看手动计算子元素的 margin-right 实现的左对齐
2.2 子元素item宽度不固定,列数是不固定
2.2.1 仍可使用 margin-right: auto
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| .container { display: flex; justify-content: space-between; flex-wrap: wrap; flex-direction: row; width: 500px; }
.list { height: 100px; background-color: skyblue; margin: 10px; }
.list:nth-child(2n) { background: rosybrown; }
.container:nth-of-type(1)> :last-child { margin-right: auto; }
|
2.2.2 使用 after 伪元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| .container { display: flex; justify-content: space-between; flex-wrap: wrap; flex-direction: row; width: 500px; }
.list { height: 100px; background-color: skyblue; margin: 10px; }
.list:nth-child(2n) { background: rosybrown; }
.container::after { content: ''; flex: auto; }
|
2.3 通用的方法
1 2 3 4
| .container:after{ content: ""; width: 32%; }
|
点击使用 after 伪元素实现左对齐
参考资料:
让CSS flex布局最后一行列表左对齐的N种方法