flex 布局下 space-between/space-around 的使用

  • 在页面布局中,我们会常用到 flex 布局实现一行多列/多行多列元素均匀排列,需要设置 justify-content: space-between 或者 justify-content: space-around (space-between可以简单理解为元素两端对齐,间距相同,space-around可以简单理解每个元素左右间距相等)。

  • 对于多行多列的情况,往往会出现最后一行的元素不满一行,这时候头疼的事情出现了。
    space-between:

space-around:

  • 为了页面美观,最后一行元素要求呈现左对齐的效果。这种情况下,我们可以通过伪元素的方式去解决。

(1) 当每行为三列时,直接设置伪元素的宽度和子元素宽度一致(适用于 space-between)

// index.less
.flex-wrap {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  // 相当于增加了一个子元素
  &::after {
    content: "";
    width: 30%;
  }

  .flex-item {
    width: 30%;
    height: 50px;
    margin-bottom: 30px;
    text-align: center;
    line-height: 50px;
    border: 1px solid #dd0000;
  }
}

【总结】:使用简单,但有一定局限性,原因在于我们并不能确定最后一行缺失几个子元素,也就是伪元素的宽度需要设置为多少。找到原因后,可以想到两种解决方法:一是计算缺失的子元素个数,二是设置伪元素宽度为最后一行的剩余宽度。

(2)计算缺失的子元素个数

通过 list 的长度和列的数量来计算最后一行缺失的元素个数,然后在页面中添加相应数量的占位元素。

// index.tsx
const arr = new Array(6).fill(1);
const colNum = 4;

const virtualNum = colNum - (arr.length % colNum);
const virtualArr = new Array(virtualNum).fill(1);

export default function Flex() {
  return (
    <div className="flex-wrap">
      {arr.map((item: number) => {
        return <div className="flex-item">{item}</div>;
      })}
      {virtualArr.map((item: number) => {
        return <div className="virtual-item"></div>;
      })}
    </div>
  );
}


// index.less
.flex-wrap {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  // justify-content: space-around;
  justify-content: space-between;

  .flex-item {
    width: 22%;
    height: 50px;
    margin-bottom: 30px;
    text-align: center;
    line-height: 50px;
    border: 1px solid #dd0000;
  }

  .virtual-item {
    content: "";
    width: 22%;
    height: 0;
  }
}

space-between:

space-around:

(3)设置伪元素宽度为最后一行的剩余宽度

利用flex布局的特点,让伪元素占最后一行剩余宽度,要注意的是,需要设置好每个元素的间距。

.flex-wrap {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  //justify-content: space-around;
  justify-content: space-between;

  &::after {
    content: "";
    flex: auto;
  }

  .flex-item {
    width: 22%;
    height: 50px;
    margin-bottom: 30px;
    margin-right: calc((100% - 22% * 4) / 3);
    text-align: center;
    line-height: 50px;
    border: 1px solid #dd0000;
    &:nth-child(4n) {
      margin-right: 0;
    }
  }
}

不设置元素间距的情况:

posted @ 2022-03-22 19:42  shellon  阅读(8318)  评论(0编辑  收藏  举报