Flex给我们的布局带来了很大的方便 ,但有时候也会碰到一些问题,比如space-between最后一行元素的排列问题

假设:当前有五个元素,每块元素长度固定,三个为一行。

1
2
3
4
5
6
7
  <ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
ul {
width: 300px;
height: 400px;
background: #f0f0f0;
list-style: none;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;
padding: 5px;
}
ul li {
width: 90px;
height: 50px;
text-align: center;
line-height: 50px;
background: pink;
border-radius: 10px;
}

问题:由于space-between就是两端布局,当最后一行不满三个的时候,最后一排会分在两端。

解决方案一: 使用after伪元素

1
2
3
4
ul:after{
content: '';
width: 90px; # 每块的长度
}

加入后可以看到修改的效果

但是这种仅限一行为三个适用,多个会出现问题。

解决方案二: 添加空白元素补齐

这种实现比较常见,难点就是获取动态长度从而补齐,示例为Vue代码实现。

1
2
3
4
5
6
7
8
<div class="kg-list-container" ref="listContainer">
<div v-for="item in 6" class="list-item">
<p class="kg-background"></p>
<p class="item-title">title</p>
</div>
<div v-for="item in paddingLength" class="list-item">
</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export default {
data () {
return {
paddingLength: 0
}
},
mounted: function () {
let self = this
this.reCalcPaddingLength()
window.onresize = function () {
self.reCalcPaddingLength()
}
},
methods: {
// 解决space-between布局的问题,添加div填充空位
reCalcPaddingLength () {
let outerLength = this.$refs.listContainer.clientWidth // 外面div的宽度
let listLen = 6 // 子元素个数,自行调整
let lineCapacity = Math.floor(outerLength / 300) // 计算每一行的容量
this.paddingLength = listLen % lineCapacity === 0 ? 0 : (lineCapacity - listLen % lineCapacity) // 得出需要添加的空块
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
.kg-list-container {
margin-top: 20px;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.list-item {
margin: 0px 0px 40px 0px;
width: 300px;
height: 220px;
border: solid 1px inherit;
border-radius: 10px;
overflow:hidden;
}
.kg-background {
background: black;
height: 180px;
margin: 0px;
}
.list-item {
width: 300px;
height: 220px;
}