css3 flex居中布局,最后一行如何居左排版

css3 flex布局时,经常会用到 justify-content: space-between | space-around | center 实现居中布局。
但是最后一行我们又希望居左排版,除了使用 js ,还有其他办法么?本文介绍两种方法。

方法一: 添加空白盒子

常见布局应该是这样:

1
2
3
4
5

但是这样有个问题,最后一行会两端对齐,并不会居左。
如果外层固定宽度,可以通过增加空白盒子实现。如下:

1
2
3
4

效果实现了,但是并不完美,添加了无用的 html 节点。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<div class="ul-1">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item empty"></div>
<div class="item empty"></div>
</div>
<style>
.ul-1 {
display: flex;
justify-content: space-between;
/* justify-content: space-around; */
flex-wrap: wrap;
width: 210px;
}
.ul-1 .item {
width: 60px;
height: 40px;
line-height: 40px;
text-align: center;
color: #fff;
background-color: #006b6b;
list-style: none;
margin-bottom: 20px;
}
.ul-1 .item.empty {
background: #ddd;
}
</style>

方法二:通过伪元素实现

布局不使用 justify-content: space-between | space-around
使用 justify-content: centermargin 实现空白间距,
使用 after 伪元素实现最后一行居左排版。效果如下:

最后一行留两个

1
2
3
4
5

最后一行留一个

1
2
3
4

单独一行

1
2

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div class="ul-2">
<div class="item">1</div>
<div class="item">2</div>
</div>

<style>
.ul-2 {
display: flex;
justify-content: center;
flex-wrap: wrap;
width: 210px;
}
.ul-2:after {
content: '';
flex: auto;
}
.ul-2 .item {
margin: 0 5px;
width: 60px;
height: 40px;
line-height: 40px;
text-align: center;
color: #fff;
background-color: #2a7600;
list-style: none;
margin-bottom: 20px;
}
</style>

欢迎大佬给出更好的方法

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2020-01-14/css3-flex-last-line-left/

如果您觉得文章不错,可以点击文章中的广告支持一下!