css样式flex布局设置元素最后一列自动靠左对齐

html代码

  <div class="container">
        <div class="list">1</div>
        <div class="list">2</div>
        <div class="list">3</div>
        <div class="list">4</div>
        <div class="list">5</div>
        <div class="list">6</div>
        <div class="list">7</div>
    </div>

方法一

列数确定的情况下

.container {
    display: flex;
    flex-wrap: wrap;/* 开启换行 */

}
.list {
    width: 24%; 
    height: 100px;
    background-color: skyblue;
    margin-top: 15px;
}
/* :nth-child(4n)中的4n表示索引(这里的索引是从1开始)是4的倍数的元素,此处表示4,8,12这些元素将被选中 */
/* :not()表示不是括号中的元素 */
/* 所以此处表示不是4倍数的元素设置margin-right值 */
.list:not(:nth-child(4n)) {
    margin-right: calc(4% / 3);/* margin-right值自动计算剩余百分比空间 */
}

 方法二

同样也是确定列数的情况下

.container {
    display: flex;
    flex-wrap: wrap;/* 开启换行 */
    justify-content: space-between;/* 两端对齐 */
}
.list {
    width: 24%; 
    height: 100px;
    background-color: skyblue;
    margin-top: 15px;
}
/* last-child表示选择最后一个元素 */
/* 如果最后一行是3个元素 */
.list:last-child:nth-child(4n - 1) {
    margin-right: calc(24% + 4% / 3);/* 此值表示一个元素的宽度加一个元素的margin-right值 */
}
/* 如果最后一行是2个元素 */
.list:last-child:nth-child(4n - 2) {
    margin-right: calc(48% + 8% / 3);/* 此处括号内也可以写48% + 4% / 3*2,表示两个元素宽度加两个margin-right值 */
}
/* 如果最后一行是1个元素 */
/* 只有一个元素justify-content: space-between就可以自动对齐了 */

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值