第一种办法:
因为每一行元素是固定的,所以我们拿5个元素为一行作为案例,废话不多说直接上案例.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.flex {
width: 700px;
height: 400px;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.flex>div{
background: skyblue;
width: 120px;
height: 120px;
}
//最后一个元素在第2列的情况
.flex div:last-child:nth-child(5n + 2) {
margin-right: calc((100% - 120px) / 4 * 3);
}
//最后一个元素在第3列的情况
.flex div:last-child:nth-child(5n + 3) {
margin-right: calc((100% - 120px) / 4 * 2);
}
//最后一个元素在第4列的情况
.flex div:last-child:nth-child(5n + 4) {
margin-right: calc((100% - 120px) / 4 * 1);
}
</style>
</head>
<body>
<div class="flex">
<div>库里</div>
<div>科比</div>
<div>詹姆斯</div>
<div>欧文</div>
<div>杜兰特</div>
<div>乔丹</div>
<div>乔治</div>
</div>
</body>
</html>
第二种办法:
直接使用网格布局,比较方便.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.flex {
width: 700px;
height: 400px;
display: grid;
justify-content: space-around;
grid-template-columns: repeat(auto-fill, 120px);
grid-gap: 20px;
}
.flex>div{
background: skyblue;
width: 120px;
height: 120px;
}
</style>
</head>
<body>
<div class="flex">
<div>库里</div>
<div>科比</div>
<div>詹姆斯</div>
<div>欧文</div>
<div>杜兰特</div>
<div>乔丹</div>
<div>乔治</div>
</div>
</body>
</html>
第三种办法:
直接计算 ,分配剩余空间
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<style>
.box {
display: flex;
flex-wrap: wrap;
width: 40%;
border: 1px solid red;
}
.son1 {
width: 100px;
height: 100px;
background: deepskyblue;
}
.son2 {
width: 100px;
height: 100px;
background: pink;
}
.son3 {
width: 100px;
height: 100px;
background: yellow;
}
.son4 {
width: 100px;
height: 100px;
background: green;
}
.box > div {
--n: 5;
--space:calc(100% - var(--n) * 100px);
--h:calc(var(--space)/var(--n) /2);
margin: 10px var(--h);
}
</style>
<div class="box">
<div class="son1">1</div>
<div class="son2">2</div>
<div class="son3">3</div>
<div class="son4">4</div>
<div class="son1">1</div>
<div class="son2">2</div>
<div class="son3">3</div>
<div class="son4">4</div>
<div class="son1">1</div>
<div class="son2">2</div>
<div class="son3">3</div>
<div class="son4">4</div>
</div>
</body>
</html>