點燈坊

失くすものさえない今が強くなるチャンスよ

使用 items-stretch 在換列下處理 Cross Axis 高度

Sam Xiao's Avatar 2021-02-23

實務上除了在 Main Axis 方向對齊外,若外層 <div> 有高度且 Item 有換列,若也需同時達成 Item 高度與外層 <div> 同高,可使用 items-stretch 達成。

Version

Tailwind CSS 2.0.3

items-start

start000

當 Flexbox 換列時,紅色部分為其內部 flex line,若 item 並沒有設定 height,align-stretch 會將 item height 自動 stretch 成 flex line 的 height。

<template>
  <div class="flex flex-wrap items-stretch w-full h-screen">
    <div class="w-3/12 m-2">1</div>
    <div class="w-3/12 m-2">2</div>
    <div class="w-3/12 m-2">3</div>
    <div class="w-3/12 m-2">4</div>
    <div class="w-3/12 m-2">5</div>
  </div>
</template>

第 2 行

<div class="flex flex-wrap items-stretch w-full h-screen">

設定 box 的 style:

  • flex:使用 Flexbox
  • flex-wrap:當各 item 總 width 超越 box width 時自動換列
  • items-stretch:各 item 的 height 會 stretch 成 flex line 的 height,這也是預設值
  • w-full:設定 box 的 width
  • h-screen:設定 box 的 height

第 3 行

<div class="w-3/12 m-2">1</div>

設定各 item 的 style:

  • w-3/12:設定各 item 的 width
  • m-2:設定各 item 的 margin

故意沒設定 item 的 height,將由 items-stretch 決定 height

Conclusion

  • items-stretch 在沒有換列時,其 flex line 只有一列,且 height 剛好等於 box height,因此看不出 flex line 概念;但若牽涉換列時,就可明顯看出 items-stretch 是根據 flex line 的 cross axis 所延展

Reference

Tailwind CSS, items-stretch