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;
    }
  }
}

不設置元素間距的情況:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM