问题情境:
在flex布局下,多行排列,如何让flex布局最后一行没有排满时,向左对齐 排列且与上面的行间距相同
实现效果:
解决方案一 (利用父级的 :after 占位)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style type="text/css">
li {
list-style: none;
}
.List {
width: 100%;
box-sizing: border-box;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
padding: 10px;
}
.List:after{
content: "";
flex: auto;
}
.item {
/* 宽度是固定好的 */
width: 220px;
height: 60px;
background-color: azure;
margin-bottom: 10px;
border: 1px solid red;
/*这个数值需要自己去调*/
margin-right: 17px;
}
.item:nth-child(5n){
/* 尽量让item在list中居中,两边都没有margin */
margin-right: 0;
}
</style>
<body>
<div id="" style="width: 1200px;margin: auto;background-color: #cccccc;height: 500px;">
<ul class="List">
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
</ul>
</div>
</body>
</html>
重要代码:要加after以及每个item的margin-right
.List:after{
content: "";
flex: auto;
}
解决方案二(利用:last-child和:nth-child()占位)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.container {
overflow: hidden;
}
.container .content {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
margin-left: -2%;
}
.container .item {
color: #fff;
line-height: 1.5em;
text-align: center;
width: 23%;
height: 100px;
background-color: #2193b0;
margin-top: 2%;;
margin-left: 2%;
}
.container .item:last-child:nth-child(4n-2) {/* 如果是2个元素 */
margin-right: calc(100% - 46% - 4%);
}
.container .item:last-child:nth-child(4n-1) {/* 如果是3个元素 */
margin-right: calc(100% - 69% - 6%);
}
</style>
<body>
<div class="container">
<div class="content">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
<div class="item">item 4</div>
<div class="item">item 5</div>
<div class="item">item 6</div>
<div class="item">item 7</div>
<div class="item">item 8</div>
<div class="item">item 9</div>
<div class="item">item 10</div>
</div>
</div>
</body>
</html>
解决方案三(补位添加节点法,这种方案适用于多种排列方式)
<div class="flex">
<div class="flex-item" v-for="item in len">列表</div>
<div class="list" v-for="item in (row - len % row)" v-if="len%row > 0"></div>
</div>
data(){
return {
len : 14, // 一共有多少个
row: 4 // 有几行(实际情况,行数应该计算得来,这里偷懒了)
}
}
.flex{
display: flex;
flex-wrap: wrap;
justify-content:space-between;
justify-items: center;
text-align: justify;
}
.flex-item{
width:20%;
border:1px solid #ff6600;
margin-bottom: 10px;
padding: 10px 5px;
display: flex;
justify-content: center;
}
.list{
content: '';
width: 20%;
border:1px solid transparent;
padding: 5px;
overflow: hidden;
}
flex : 0 0 24%;
参考链接 https://juejin.cn/post/6893040128206307342#heading-8
https://juejin.cn/post/6976973127909654559