在 CSS3 支援 flexbox 排版以後,相信許多人已經使用了 flexbox,還沒使用過的可以去玩 Flexbox Froggy 學習一下 XD
最近使用 flexbox 製作 RWD 網站時,順便弄清楚了 flex-basis, flex-grow , flex-shrink
在這邊紀錄一下
flex-basis
決定 flexbox 排版的 item 的初始寬/高(取決於 flex-direction 的方向).
- auto 預設值,根據 item 的內容決定寬/高
- <width/height> 指定特定的寬/高,可以是數值也可以是比例.
Q: flex-basis 和 width/height 有什麼不一樣?
A:
當 flex-direction: row 時,flex-basis 會決定了 width.
當 flex-direction: column 時,flex-basis 會決定了 height.
備註: position: absolute 的 elment 因為不會是 flexbox 排版因此無法透過 flex-basis 設定 width/height.
flex-grow
決定 flexbox 排版的 item 如何分配剩餘的空間.
舉個例子,以往如果要做單/雙側欄排版時,我們必須使用百分比或 calc 來達成,現在使用 flexbox + flex-grow 就可以輕易地達成!
有個特別的地方是當 flex-grow 介於 0-1 時,剩餘空間將不會被分配完.
Flex values between 0 and 1 have a somewhat special behavior: when the sum of the flex values on the line is less than 1, they will take up less than 100% of the free space.
簡單來說,在 flexbox 排版底下的所有 item 預設的 flex-grow 會是 0,若有剩餘空間,則會以如下算法去分配空間:
(每個 item 的 flex-grow / 全部 item 的 flex-grow 總和) x 剩餘空間
ps. 全部 item 的 flex-grow 總和最小為 1
舉個例子:
flex-shrink
當空間有限時,決定如何分配縮小的比例在每個 item,預設值為 1
計算方法也與 flex-grow 相當接近
(每個 item 的 flex-shrink / 全部 item 的 flex-shrink 總和) x (item 寬/高)
ps. 全部 item 的 flex-grow 總和最小為 1
來個例子(在 jsfiddle 拖拉會比較有感):
最後,補充一下使用 flexbox 排版需要注意的小細節
依照 w3c spec 有特別註記 flexbox 裡面的 item 預設會是 min-width: auto/min-height: auto ,並且會是 overflow: visible
To provide a more reasonable default minimum size for flex items, this specification introduces a new
autovalue as the initial value of themin-widthandmin-heightproperties defined in CSS 2.1.
On a flex item whose
overflowisvisiblein the main axis, when specified on the flex item’s main-axis min-size property, specifies an automatic minimum size. It otherwise computes to0.
常見的問題可能是在實作上方的雙側欄或是僅帶有 header/footer 的單頁式網站(100vh/100vw)
會發現 flexbox item 就算宣告 flex-shrink仍然會因為 item 內容而無法進而縮放.
這時可以試著將 flexbox item 加上以下屬性
[code lang=“css”] min-width: 0; min-height:0; overflow: hidden; [/code]
就可以正常縮小 item 了 🎉
參考資料:
https://cythilya.github.io/2017/04/06/flexbox-advance/
https://www.w3.org/TR/css-flexbox-1/
https://stackoverflow.com/questions/36247140/why-dont-flex-items-shrink-past-content-size