淺談Flex佈局

haqiu發表於2019-05-05

何為Flex佈局

傳統的佈局解決方案,是基於盒子模型,利用position + margin + float來完成;但這種佈局方案對部分佈局方式很不友好,比如水平垂直居中

Flex佈局是W3C提供的一種新型佈局解決方案,利用彈性盒子佈局,可以做到響應式設計,更好的適配PC端和移動端

Flex基本概念

採用Flex佈局的元素成為Flex容器(flex container),內部元素成為Flex專案(flex item)

淺談Flex佈局

Flex容器內部分為主軸(main axis)和交叉軸(cross axis);專案分為主軸(main size)和交叉軸(cross size)

  • 塊元素設定flex: display: flex;
  • 行內元素設定flex:display:inline-flex;

Flex容器屬性

flex-direction

決定內部專案在主軸上如何排列

flex-direction: row | row-reverse | column | column-reverse

  • row:專案從坐向右排列
  • row-erverse:專案從右向左排列
  • column:專案從上往下排列
  • colum-reverse:專案從下往上排列

row
row-reverse
column
column-reverse

flex-warp

決定內部專案的換行方式

flex-warp: nowarp | warp | warp-reverse

  • nowarp: 不換行
  • warp:換行,換行元素在下方
  • warp-reverse:換行,換行元素在上方

nowarp
warp
淺談Flex佈局

flex-flow

flex-direction和flex-warp的簡寫形式,預設是row nowarp

flex-flow: < flex-direction > < flex-wrap >;

justify-content

決定專案在主軸上的對齊方式

justify-content: flex-start | flex-end | center | space-between | space-around

  • flex-start:左對齊
  • flex-end:右對齊
  • center:居中對齊
  • space-between:兩端對其,專案之間間隔相等
  • space-around:每個專案兩側間隔相等,專案之間的間隔比專案與邊框間隔大一倍
    淺談Flex佈局
    淺談Flex佈局
    淺談Flex佈局
    淺談Flex佈局
    淺談Flex佈局

aline-items

決定專案在交叉軸上的對齊方式

aline-items: flex-start | flex-end | center | baseline | stretch

  • flex-start:交叉軸起點對其,上對其
  • flex-end:交叉軸終點對其,下對齊
  • center:垂直居中
  • baseline:專案的第一行文字基線對齊
  • stretch(預設值):如果專案未設定高度或auto,則專案高度填滿容器
    淺談Flex佈局
    淺談Flex佈局
    淺談Flex佈局
    淺談Flex佈局
    淺談Flex佈局

aline-content

定義了多軸線的對其方式,如果只存在一條軸線,則不起作用

aline-content: flex-start | flex-end | center | stretch | space-between | space-around

Flex專案屬性

order

定義專案的排列順序,數值越小排列越靠前,預設為0,負值有效

flex-grow

定義專案的放大比例,預設為0

flex-shrink

定義了專案的縮小比例,預設為1;負值無效

flex-basis

定義了在分配多餘空間之前,專案佔據的主軸空間,預設值為專案本來大小

flex

flex-grow, flex-shrink 和 flex-basis的簡寫,預設值為0 1 auto

align-self

允許單個專案有與其他專案不一樣的對齊方式,可覆蓋align-items屬性。預設值為auto,表示繼承父元素的align-items屬性,如果沒有父元素,則等同於stretch。

相關文章