【CSS基礎】Flex彈性佈局

在flex容器中默認存在兩條軸,水平主軸和垂直的交叉軸,這是默認設置,固然能夠經過修改相關屬性使垂直方向變爲主軸,水平方向變爲交叉軸,在容器中,每一個單元塊稱爲flex item,每一個flex item佔據主軸空間爲main size,佔據交叉軸空間爲cross size。瀏覽器

Flex容器

首先實現flex佈局須要先指定一個容器,任何一個容器均可以被置頂爲flex佈局,這樣容器內的元素就可使用flex來進行佈局。佈局

.container {
    display: flex | inline-flex;
}

flex生成一個塊狀的flex容器盒子,inline-flex生成一個行內flex容器盒子,如下六種屬性能夠設置在容器上:flex

  1. flex-direction
  2. flex-wrap
  3. flex-flow
  4. justify-content
  5. align-items
  6. align-content

flex-direction

.container {
    display:flex;
    flex-direction: row | row-reverse | column | column-reverse;
}

flex-direction決定了主軸的方向,默認值是row。spa

row:主軸方向爲水平方向,起點在左端;
row-reverse:主軸方向爲水平方向,起點在右端
column:主軸方向爲豎直方向,起點在上端
column:主軸方向爲豎直方向,起點在下端

flex-wrap

.container {
    display:flex;
    flex-wrap:nowrap | warp | wrap-reverse;
}

flex-wrap決定容器內項目是否可換行,默認值nowrap。code

nowrap:不換行,項目尺寸會隨之調整
wrap:超出換行,且第一行在上方
wrap-reverse:超出換行,且第一行在下方

flex-flow

.container {
    display:flex;
    flex-flow:<flex-direction> || <flex-wrap>;
}

flex-flow是flex-direction和flex-wrap的簡寫,其默認值爲row nowrap
繼承

justify-content

.container {
    display:flex;
    justify-content:flex-start | flex-end | center | space-between | space-around;
}

justify-content定義了項目在主軸上的對齊方式,默認值爲flex-startit

flex-start:左對齊
flex-end:右對齊
center:居中
space-between:兩端對齊,把剩餘空間等分紅間隙
space-around:每一個項目兩側的間隔相等

align-items

.container {
    display:flex;
    align-items:flex-start | flex-end | center | baseline | stretch;
}

align-items定義了項目在交叉軸上的對齊方式,默認值爲stretchio

stretch:若是項目沒有設置高度或者爲auto,將佔滿整個容器的高度
flex-start:交叉軸起點對齊
flex-end:交叉軸終點對齊
center:中點對齊
baseline:項目的第一行文字的基線對齊

align-content

.container {
    display:flex;
    align-content:flex-start | flex-end | center | space-between | space-around | stretch;
}

align-content:定義了多根軸線的對齊方式,若是項目只有一個軸線,那麼該屬性將不起做用。好比flex-wrap:nowrap;容器只有一根軸線,align-content就不起做用。默認值爲stretch。當存在多條軸線時,多條軸線在垂直方向上的佈局。容器

flex項目

有如下6中定義在item上的屬性:項目

  1. order
  2. flex-basis
  3. flex-grow
  4. flex-shrink
  5. flex
  6. align-self

order

.item {
    order:<number>;
}

order定義項目在容器中的排列順序,數值越小排列越靠前,默認值爲0。

flex-basis

.item {
    flex-basis:<length> | auto;
}

flex-basis定義了在分配多餘空間以前,項目佔據主軸空間,瀏覽器根據這個屬性,計算主軸是否有多餘空間,默認值爲auto,即項目自己的寬高。flex-basis須要跟flex-grow和flex-shrink配合使用才能發揮效果。

flex-grow

.item {
    flex-grow:<number>;
}

flex-grow定義項目的放大比例,默認值爲0,即若果存在剩餘空間,也不放大。當全部項目的flex-grow屬性值爲1,則它們將等分剩餘空間,若是一個項目flex-grow爲2,其餘爲1,則前者佔據的剩餘空間將比其餘項多一倍。若是全部項flex-basis的值排列完後發現空間不夠,且flex-wrap:nowrap時,此時flex-grow則不起做用。

flex-shrink

.item {
    flex-shrink:<number>;
}

flex-shrink定義項目的縮小比例,默認值爲1,若空間不夠,且全部項的值爲1,則全部項等比例縮小,若是一項flex-shrink屬性爲0,其餘項都爲1,則前者不縮小。

flex

.item {
    flex:auto | none | <flex-grow> | <flex-shrink> | <flex-basis>;
}

flex是flex-grow、flex-shrink、flex-basis三個屬性的縮寫。

auto:三個屬性的值爲 1 1 auto
none:三個屬性的值爲 0 0 auto

align-self

.item {
    align-self:auto | flex-start | flex-end | center | baseline | stretch;
}

algn-self容許單個項目有與其餘項目不同的對齊方式,單個項目的algn-self會覆蓋align-items屬性,默認值爲auto,表示繼承父元素的align-items屬性。

相關文章
相關標籤/搜索