# CSS Flex 排版 flex屬性主要分成`容器`和子層的`物件` 為什麼要分兩種 因為子層`物件`本身也可以是`容器`讓更下層的`物件`使用 所以flex屬性才需要區分成`容器`和`物件` 再來是flex本身就是非常強大的RWD排版語法 flex練熟的話就可以不用bootstrap也能排出很好的RWD版面(不考慮細節美化) 目前主流的Web App很多都已經改成flex排版 可以參考: * twitch * discord ###### tags: `web`,`css`, `flex` ## 基本語法 ### 父層容器 ```htmlmixed= <div class="flex-container"> <div>1</div> <div>2</div> <div>3</div> </div> ``` ```css= .flex-container { display: flex; } ``` ### 子層物件 ```htmlmixed= <div class="flex-container"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> ``` ```css= .flex-container { display: inline-flex; } .flex-items { flex-grow: 1; } ``` ## 詳細語法說明 ### 父層容器 .flex-container * **display** * flex * inline-flex * **flex-flow** * `flex-flow: flex-direction flex-wrap|initial|inherit;` * 為以下兩種的簡略寫法: * **flex-direction** * `flex-direction: row|row-reverse|column|column-reverse|initial|inherit;` * default: `flex-direction: row;` * `row` - 左上開始往右 * `row-reverse` - 右上開始往左 * `column` - 左上開始往下 * `reverse` 左下開始往上 * **flex-wrap** * `flex-wrap: nowrap|wrap|wrap-reverse|initial|inherit;` * default: `flex-wrap: nowrap;` * `nowrap` - 不換行 * `wrap` - 換行 * `wrap-reverse` - 從左下往右開始,再往上換行 * **justify-content** * `justify-content: flex-start|flex-end|center|space-between|space-around|initial|inherit;` * default: `justify-content: flex-start;` * `flex-start` - 靠左 * `flex-end` - 靠右 * `center` - 置中 * `space-between` - 分散(左右不留空) * `space-around` - 平均分散(左右留空) * **align-items** * `align-items: stretch|center|flex-start|flex-end|baseline|initial|inherit;` * default: `align-items: stretch;` * `stretch` - 上下高度自動滿版 * `center` - 垂直置中不滿版 * `flex-start` - 置頂不滿版 * `flex-end` - 置底不滿版 * `baseline` - 以文字基線來垂直置中 * **align-content** * `align-content: stretch|center|flex-start|flex-end|space-between|space-around|initial|inherit;` * default: `align-content: stretch;` * 先用`flex-wrap`排版完,再用排版完的區域調整對齊位置 * `stretch` - 每一行都靠上,行分散(沒設定高度時會自動滿版) * `center` - 全部往父容器中心靠 * `flex-start` - 全部往上靠 * `flex-end` - 全部往下靠 * `space-between` - 上下分散(上下不留空) * `space-around` - 上下平均分散(上下留空) ### 子層物件 .flex-items * **order** * `order: number|initial|inherit;` * default: `0` * 從1開始由小到大排序 * **flex** * flex為以下3種屬性的簡化寫法 * 例: `flex: 0 1 auto;` * **flex-grow** * `flex-grow: number|initial|inherit;` * default: `flex-grow: 0;` * 寬度佔比: 同一排總合當分母,自己當分子 * 同一行全部設`1`且有設定基礎寬度時,不足寬度會自動加寬滿版,超過寬度時會自動換行,算是非常強大的rwd語法 * **flex-shrink** * `flex-shrink: number|initial|inherit;` * default: `flex-shrink: 1;` * 大於1收縮,0以下變寬 * **flex-basis** * `flex-basis: number|auto|initial|inherit;` * default: `flex-basis: auto` * 基礎寬度或高度,依照排序方向決定(之後還是會依照flex特性動態調整) * align-self * `align-self: auto|stretch|center|flex-start|flex-end|baseline|initial|inherit;` * default: `align-self: auto;` ## 參考資料 * [W3Schools - CSS Flexbox](https://www.w3schools.com/css/css3_flexbox.asp)