CSS布局之彈性布局


Flex(彈性布局),是一種響應式布局,能自動伸縮盒模型達到自適應的效果。

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,可將元素聲明為行內彈性容器。

  1. flex-direction屬性

flex-direction指定主軸(main cross)的方向,即元素排列的方向。

// 需先聲明為flex布局
flex-direction: row | row-reverse | column | column-reverse

// 屬性解釋:
row: 水平方向,從左往右
row-reverse: 水平方向,從右往左
column: 垂直方向,從上往下
column-reverse: 垂直方向,從下往上
  1. flex-wrap屬性

flex-wrap屬性,指定彈性項目的換行方式,即彈性項目超過一行時如何換行。

flex-wrap: no-wrap | wrap | wrap-reverse

// 屬性解釋:
no-wrap: 不換行(默認)
wrap: 正常換行
wrap-reverse: 換行,第一行在下方,從下往上換行
  1. flex-flow屬性

flex-flow屬性,為flex-directionflex-wrap的合並屬性。

// 第一個為flex-direction,第二個為flex-wrap
flex-fow: <flex-direction> <flex-wrap>
  1. 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: 項目周圍的空間相等,但空隙不折疊
  1. 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)
  1. 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: 拉伸(默認),拉伸項目以布滿縱軸長度
  1. 為什么沒有justify-items屬性呢?

盡管flex看起來像二維布局,但其實是個一維布局,縱軸(cross axis)沒有換行(wrap)的行為,自然就沒有justify-items屬性。

彈性項目

盡管彈性容器已經有設置彈性項目的各種布局行為,但總有個別彈性項目需要自定義布局方式。

  1. order屬性

order屬性,指定彈性項目的排列序號,數值越小越靠前。

order: <integer>
  1. flex-grow屬性

flex-grow屬性,指定彈性項目在有空余空間的放大比例。

// 默認為0:表示即使有剩余空間也不放大
flex-grow: <number>
  1. flex-shrink屬性

flex-shrink屬性,指定彈性項目在空間不夠時的縮小比例。

// 默認為1:表示空間不夠時項目將縮小
flex-shrink: <number>
  1. flex-basis屬性

flex-basis屬性,指定彈性項目的基本長度。

flex-basis: <length>
  1. flex屬性

flex屬性,為flex-growflex-shrinkflex-basis的合並屬性。

flex: flex-grow,flex-shrink,flex-basis
// 補充:
默認: 0,1,auto
auto: 1,1,auto
none: 0,0,auto
  1. 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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM