# CSS flex 圖解 ###### tags: `CSS` 學習資源: [圖解:CSS Flex 屬性一點也不難 | 卡斯伯](https://www.casper.tw/css/2017/07/21/css-flex/) [CSS Flexbox Layout | Treehouse](https://teamtreehouse.com/library/css-flexbox-layout) [Flex 排版技巧介紹 | 六角](https://courses.hexschool.com/courses/html/lectures/14727004) [A Complete Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) Flex分為內外容器,能夠讓頁面輕鬆地做出RWD的效果,更有彈性的控制佈局 :::warning * Flex 外容器屬性: * display * flex-flow * flex-direction * flex-wrap * justify-content * align-items * Flex 內元件屬性: * flex * flex-grow * flex-shrink * flex-basis * order * align-self ::: ## :pushpin:flex container 外容器 * Flexbox布局的外容器 * 內含多個內元件 ### display ```css= .container{ display:flex } ``` ### direction item排列的方向,是由direction決定,分為: * main axis 主軸(由左而右) * cross axis 十字軸(由上而下) 方向皆由左上為start,可藉由 flex-direction設置水平翻轉、垂直翻轉等  <br>  ```css= .container { display:flex; flex-direction: row; /*flex-direction: row-reverse; column; column-reverse*/ } ``` ### flex wrap 當item超出container範圍時是否換行  ```css= .container { display: flex; flex-wrap:wrap; width:300px; /*flex-wrap: nowrap; wrap; wrap-reverse;*/ } ``` ### flex flow `flex = flex-direction & flex-wrap` 同時設定方向及是否換行 ```css= .container{ flex-flow: <'flex-direction'> || <'flex-wrap'>; flex-flow: column-reverse wrap; } ``` ### justify-content 依主軸方向而定的對齊方式      ```css= .container { display: flex; justify-content: flex-start; /*justify-content:flex-end; center; space-between; space-around;*/ } ``` ### align-items 依交錯軸方向而定的對齊方式      baseline 對齊內容物的基線 ```css= .container { display: flex; justify-content: flex-start; /*justify-content:flex-end; center; stretch; baseline;*/ } ``` ## :pushpin:flex item 內容器 * 每個包含在container中item都稱為內容器 * 可以有單個或多個 * 若item無設定長寬將會隨父元素縮放 ```csss= .container{ display:flex; heigt:300px; weight:200px; } ``` ### flex flex包含三個部分,可以分開寫,也能把全部寫在flex中 * flex-grow: 內元件伸展,預設值為0,則不縮放 * flex-shrink: 內元件收縮性,預設值為1,設置0則不縮放 * flex-basis: 相對於container的百分比,預設為auto * 設置flex basis時 比例須加上grow ```css= .item{ flex:1 200px } .item2{ flex-grow:2 } ``` ### order 重新定義元件的排列順序 * 所有item order預設為0 * order為負數則往左排列 * 正數往右  ```css= .item-3 { order: -1; } .item-1{ order:1 } ``` ### align-self 課個別調整內元件交錯軸的設定 以下應用align-self讓btn靠右,margin-top上方距離自動、元件貼底 ```css= .button{ margin-top:auto; align-self:flex-end } ```  ## :pushpin:其他應用 ### nav 可用於navigation使用margin自動吸收所有間距 ```css= .container{ display:flex; justify-content: space-between; } .item-1{ margin-right: auto } ```  ### 頁尾 設定固定於頁尾的footer ```css= body{ display:flex; flex-direction:column; min-height:100vh; } .main-footer{ margin-top:auto } body{ display:flex; flex-direction:column; min-height:100vh; } .row{ flex:1 } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up