Flex(彈性布局)
,是一種響應式布局,能自動伸縮盒模型達到自適應的效果。
彈性布局由彈性容器(flex container)
和彈性項目(flex item)
組成。
在彈性容器
中,水平方向稱為主軸(main axis)
(起點main start
,終點main end
);垂直方向稱為縱軸(cross axis)
(起點cross start
,終點cross end
)。
在彈性項目
中,元素的寬度稱為main size
,高度稱為cross size
。
彈性容器
通過display: flex
屬性,可將元素聲明塊級彈性容器;通過dsplay: inline-fex
,可將元素聲明為行內彈性容器。
- flex-direction屬性
flex-direction
指定主軸(main cross)
的方向,即元素排列的方向。
// 需先聲明為flex布局
flex-direction: row | row-reverse | column | column-reverse
// 屬性解釋:
row: 水平方向,從左往右
row-reverse: 水平方向,從右往左
column: 垂直方向,從上往下
column-reverse: 垂直方向,從下往上
- flex-wrap屬性
flex-wrap
屬性,指定彈性項目的換行方式,即彈性項目超過一行時如何換行。
flex-wrap: no-wrap | wrap | wrap-reverse
// 屬性解釋:
no-wrap: 不換行(默認)
wrap: 正常換行
wrap-reverse: 換行,第一行在下方,從下往上換行
- flex-flow屬性
flex-flow
屬性,為flex-direction
和flex-wrap
的合並屬性。
// 第一個為flex-direction,第二個為flex-wrap
flex-fow: <flex-direction> <flex-wrap>
- justify-content屬性
justify-content
屬性,指定彈性內容在主軸上的排列方式。
justify-content: flex-start | flex-center | flex-end | space-between | space-around
// 屬性解釋:
flex-start: 從主軸起點(main start)到主軸終點(main end)
center: 居中
flex-end: 從主軸終點(main end)到主軸起點(main start)
space-between: 項目周圍的空間相等,但空隙會折疊
space-between: 項目周圍的空間相等,但空隙不折疊
- align-items屬性
align-items
屬性,指定彈性項目
在縱軸上的對齊方向。
align-items: flex-start | center | flex-end | base-line | stretch
// 屬性解釋:
flex-start: 項目對齊縱軸的起點(cross start)
center: 居中
flex-end: 項目對齊縱軸的終點(cross end)
baseline: 基於基線對齊
stretch: 拉伸(默認),從起點(cross start)到終點(croos end)
- align-content屬性
align-content
屬性,指定當主軸(main axis)
隨項目換行時,多條主軸線如何對齊。
align-content: flex-start | center | flex-end | space-between | space-around | stretch
// 屬性解釋:
flex-start: 從縱軸起點(cross start)到終點(cross end)
center: 居中
flex-end: 從縱軸終點(cross end)到縱軸起點(cross start)
space-between: 項目周圍的空間相等,但空隙會折疊
space-between: 項目周圍的空間相等,但空隙不折疊
stretch: 拉伸(默認),拉伸項目以布滿縱軸長度
- 為什么沒有justify-items屬性呢?
盡管flex看起來像二維布局,但其實是個一維布局,縱軸(cross axis)
沒有換行(wrap)
的行為,自然就沒有justify-items屬性。
彈性項目
盡管彈性容器
已經有設置彈性項目
的各種布局行為,但總有個別彈性項目
需要自定義布局方式。
- order屬性
order
屬性,指定彈性項目
的排列序號,數值越小越靠前。
order: <integer>
- flex-grow屬性
flex-grow
屬性,指定彈性項目
在有空余空間的放大比例。
// 默認為0:表示即使有剩余空間也不放大
flex-grow: <number>
- flex-shrink屬性
flex-shrink
屬性,指定彈性項目
在空間不夠時的縮小比例。
// 默認為1:表示空間不夠時項目將縮小
flex-shrink: <number>
- flex-basis屬性
flex-basis
屬性,指定彈性項目
的基本長度。
flex-basis: <length>
- flex屬性
flex
屬性,為flex-grow
、flex-shrink
和flex-basis
的合並屬性。
flex: flex-grow,flex-shrink,flex-basis
// 補充:
默認: 0,1,auto
auto: 1,1,auto
none: 0,0,auto
- align-self屬性
align-self
屬性,指定彈性項目
在縱軸上的對齊方式,將覆蓋掉彈性容器
的align-items
屬性。
align-self: auto flex-start | center | flex-end | base-line | stretch
// 屬性解釋:
auto: 自動
flex-start: 項目對齊縱軸的起點(cross start)
center: 居中
flex-end: 項目對齊縱軸的終點(cross end)
baseline: 基於基線對齊
stretch: 拉伸(默認),從起點(cross start)到終點(croos end)