当我们在开发项目使用flex进行盒子布局时,给子元素设置了百分比宽度,此时会出现一个问题,当设置每行三个并给父元素添加justify-content: space-between;然而子元素一共只有8个,盒子的最后一行会变成这样:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.box {
width: 45%;
height: 500px;
background-color: orange;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
}
.box .boxItem {
width: 30%;
height: 120px;
background-color: cyan;
display: flex;
justify-content: center;
align-items: center;
}
.box .boxItem:nth-child(2n) {
background-color: deeppink;
}
</style>
<body>
<div class="box">
<div class="boxItem">1</div>
<div class="boxItem">2</div>
<div class="boxItem">3</div>
<div class="boxItem">4</div>
<div class="boxItem">5</div>
<div class="boxItem">6</div>
<div class="boxItem">7</div>
<div class="boxItem">8</div>
</div>
</body>
</html>
当我们要实现这种效果时:
只需要添加一段css代码:
<style>
.box::after {
content: '';
width: 30%;
height: 0;
display: block;
}
</style>
需要注意的是,如果子元素数量不固定时,需要通过js代码实现动态修改伪类元素宽度。