排版方式(2):flex大顯神威
格式
啟用方式
在container
上設定display: flex
,下一層的標籤會變成flex物件。
先上範例,再來解釋flex物件可以有甚麼屬性。
什麼是主軸&次軸
瞭解flex可以做哪些設定之前,我們先來建立一些觀念
- 由
flow-direction
決定資料的方向
- 資料排列的方向是主軸,另一個垂直的方向就是次軸
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
常用設定
flow-direction
: 排版方向
justify-content
: 控制主軸
align-items
: 控制次軸
align-content
: 控制次軸
範例
底下是一個flex排版的範例,請大家自行取用
排版方向:flex-direction
控制排版的方向(也就是主軸的方向),以及排版的順序(也就是主軸的起始點&終點)。主要有以下幾種屬性值:
- row:水平排列
- column:垂直排列
- row-reverse:水平排列+順序倒過來
- column-reverse:垂直排列+順序倒過來
flex-direction: row
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
flex-direction: column
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
flex-direction: row-reverse

flex-direcion: column-reverse

控制主軸: justify-content
justify-content
負責控制主軸的排版
如果設定flex-direction: row
(設定主軸為水平方向),則justify-content
就會控制在水平方向上的排版。
justify-content
主要有以下幾種屬性值
- start:聚集在主軸的起點
- center:聚集在主軸的中間
- end:聚集在主軸的終點
- space-around:將margin分配到標籤的兩側
- space-between:將margin分配到標籤的中間
- space-evenly:使margin等寬
justify-content: start

justify-content: center

justify-content: end

justify-content: space-around

justify-content: space-between

justify-content: space-evenly

Project1

控制副軸-單行: align-items
jalign-items
負責控制副軸的排版
如果設定flex-direction: row
(設定主軸為水平方向,副軸則為垂直方向),則align-items
就會控制在垂直方向上的排版。
align-items
主要有以下幾種屬性值
- start:排列在副軸的起點
- center:排列在副軸的中間
- end:排列在副軸的終點
- stretch:伸長container底下的標籤在副軸方向上的長度
align-items: start

align-items: center

align-items: end

align-items: strech

flex的特性 小結
- 預設
flex-direction: row
- 預設
justify-content: start
- 預設的flex物件會等高
Project2
做一個滿版背景,中間放文字區塊
- 用flex使文字區塊置中
- 做一些簡單的美化看起來讓他好看一點
⚠️注意!
如果父層容器沒有任何高度,是無法垂直置中的!

Project 3 (Optional)
把先前做過的自我介紹做一些小改造:
- 畫面左邊1/3的部份放自己的個人簡介
- 畫面右邊2/3的部份放剩下的內容
- 使用flex來控制這兩個區塊

❓為什麼我切出來的版面兩個會一樣高呢
要怎麼做才會讓他們恢復到自身的高度
試著自己上網查相關的資料