五分鐘掌握Flex佈局

何爲Flex佈局

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

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

Flex基本概念

採用Flex佈局的元素成爲Flex容器(flex container),內部元素成爲Flex項目(flex item) spa

Flex容器內部分爲主軸(main axis)和交叉軸(cross axis);項目分爲主軸(main size)和交叉軸(cross size)設計

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

Flex容器屬性

flex-direction

決定內部項目在主軸上如何排列3d

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

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

row
row-reverse
column
column-reverse

flex-warp

決定內部項目的換行方式blog

flex-warp: nowarp | warp | warp-reverse繼承

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

nowarp
warp

flex-flow

flex-direction和flex-warp的簡寫形式,默認是row nowarpit

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

justify-content

決定項目在主軸上的對齊方式

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

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

aline-items

決定項目在交叉軸上的對齊方式

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

  • flex-start:交叉軸起點對其,上對其
  • flex-end:交叉軸終點對其,下對齊
  • center:垂直居中
  • baseline:項目的第一行文字基線對齊
  • stretch(默認值):若是項目未設置高度或auto,則項目高度填滿容器

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。

相關文章
相關標籤/搜索