# FlexBox ###### tags: `待補充` `CSS` > CSS3 為了適應不同螢幕尺寸和顯示設備而生的佈局模式。 ### Flexbox 核心元素 #### Flex container 容器 > 包裹住物件的**父元素**。 ```css= .container { display: flex; /**容器"不會"隨物件變化**/ display: inline-flex; /**容器"會"隨物件變化**/ } ``` #### Flex item 物件 > 被容器包裹住的**子元素**。 #### Axes 軸 > 主軸的方向將會影響容器內的元素排序順序、方向。 - [flex-direction](#flex-direction) 可以決定**主軸**的方向。 - [flex-wrap](#flex-wrap) 可以變更**副軸**的方向。 ### Flexbox 屬性 #### `flex-direction` > - flex-direction 可以決定主軸的方向。 > - row 為預設值。 ```css= .container { flex-direction: row; /**主軸從左至右**/ flex-direction: row-reverse; /**主軸從右至左**/ flex-direction: column; /**主軸由上至下**/ flex-direction: column-reverse; /**主軸由下至上**/ } ``` #### `flex-wrap` > - 設定當元素超出容器時該怎麼顯示。 > - nowrap 為預設值。 ```css= .container { flex-wrap: nowrap; /**不換行**/ flex-wrap: wrap; /**換行**/ flex-wrap: wrap-reverse; } ``` :::warning **wrap-reverse:** wrap-reverse 所更改的為「**副軸**」並非主軸,因此擺放的規則為: 主軸從左至右,副軸由下至上 ![](https://i.imgur.com/1REUONH.png =70%x) ::: #### `order` > - Flexbox 提供每個物件一個 order 值,會依照大小排列。 > - 每個物件預設是 order: 0。 ```css= #box3 { order: -1; } ``` ![](https://i.imgur.com/Ys9GBCn.png =70%x) #### justify-content #### align-items #### align-content #### align-self #### flex-grow > - 依照設定比例分配剩餘空間。 > - 預設值爲 0。 ```css= #box3 { flex-grow: 1; /**剩下的空間分一份給 box3**/ } #box4 { flex-grow: 2; /**剩下的空間分二份給 box4**/ } ``` ![](https://i.imgur.com/Kjm4weB.png =70%x) #### flex-shrink > - 空間不夠時的壓縮比例。 > - 預設值為 1。 ```css= /**假設每個 box 的大小均為 100 px**/ /**以下設定為當空間不夠時,只會壓縮 box4(預設會壓縮)**/ #box1 { flex-shrink: 0; /**當空間不夠時,box1 的壓縮比例為: * 100 *0(flex-shrink) *100(width) / 1200(容器寬)= 0 * 也就是不會壓縮 **/ } #box2 { flex-shrink: 0; } #box3 { flex-shrink: 0; } ``` #### flex-basis