使用flex布局时,盒子数量不均衡,使用justify-content: space-between || space-around 实现盒子左对齐

当我们在开发项目使用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代码实现动态修改伪类元素宽度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值