flex布局最后一行元素左对齐

需求:元素高度不固定,总数不固定,一行 6 个元素

方案一(×): 使用justify-content: space-between;自动设置列间距的情况

<template>
  <div class="ft">
    <div class="div-flex">
      <div class="item" v-for="i in 5" :key="i"></div>
    </div>
  </div>
</template>
<script>
export default {
  name: "FlexTest",
};
</script>
<style lang="less" scoped>
.div-flex {
  width: 430px;
  background-color: antiquewhite;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  .item {
    width: 100px;
    height: 100px;
    border: 1px solid #000;
    box-sizing: border-box;
    background-color: aquamarine;
    &:nth-child(n + 7) {
      margin-top: 10px;
    }
  }
}
</style>

不作处理的情况下,最后一行是这样的:
在这里插入图片描述
如果一行有 6 个元素,就要设置第一行以后的所有行间距(通过:nth-child(n + 7)设置);

现在处理最后一行的情况:
设置最后一行元素左对齐,而不是平分,有人说让最后一个元素margin-right: auto就好了,结果如下:

.item{
...
    &:last-child {
      margin-right: auto;
    }
}

在这里插入图片描述
列间距没了,既然用了space-between自动设置列间距,就是不想计算间距手动设置到 item 上,看来加了 margin-right 属性后space-between在这一行上就失效了,先手动设置一下:

    &:last-child {
      margin-right: auto;
      margin-left: 10px;
    }

在这里插入图片描述
效果不错,正是期待的结果;但是如果有 n+3 个元素时:
在这里插入图片描述
再继续控制就复杂了,放弃使用justify-content: space-between;,看来这并不是理想的方案。

方案二: 控制每一个 item 的间距

...
<style lang="less" scoped>
.div-flex {
  width: 650px;
  background-color: antiquewhite;
  display: flex;
  flex-flow: row wrap;
  .item {
    width: 100px;
    height: 100px;
    border: 1px solid #000;
    box-sizing: border-box;
    background-color: aquamarine;
    margin-right: 10px;
    &:nth-child(n + 7) { margin-top: 10px; }
    &:nth-child(6n) { margin-right: 0; }
  }
}
</style>

在这里插入图片描述
算是中规中矩的一种方案,没有任何问题,也无特色。(跟浮动的方案差不多了)

另外一种实现需求的方案:用 grid 来实现

...
.div-flex {
  width: 650px;
  background-color: antiquewhite;
  display: grid;
  // grid-template-columns: repeat(6, 100px);
  // grid-template-columns: repeat(auto-fill, 100px);
  grid-template-columns: repeat(6, 1fr);// 三种写法都行
  grid-gap: 10px;
  .item {
    width: 100px;
    height: 100px;
    border: 1px solid #000;
    box-sizing: border-box;
    background-color: aquamarine;
  }
}

这种方案来实现此需求最简单合适。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值