flex 學習筆記
flex 容器
display:flex;
把容器轉換成彈性盒,兼容寫法
display: -webkit-box; /* 老版本語法: Safari, iOS, Android browser, older WebKit browsers. */
display: -moz-box; /* 老版本語法: Firefox (buggy) */
display: -ms-flexbox; /* 混合版本語法: IE 10 */
display: -webkit-flex; /* 新版本語法: Chrome 21+ */
display: flex;
flex容器屬性
- flex-direction
決定主軸的方向;
取值:
row (水平橫向 左至右)
row-reverse (水平反向 右支左)
column (垂直 上至下)
column-reverse (垂直反向 下至上)
- flex-wrap
決定子元素是否換行
取值:
nowrap (不換行,子元素按比例分配寬/高)
wrap (正常換行 第一行在主軸起始方向)
wrap-reverse(反向換行 第一行在主軸結束方向);
- flex-flow
flex-direction屬性和flex-wrap屬性的簡寫形式,默認值爲row nowrap
取值:
由 flex-direction 和flex-wrap 的取值組合
- justify-content
決定了子元素在主軸上的對齊方式;
取值:
flex-start (靠近主軸起始方向顯示)
flex-end (靠近主軸結束方向顯示)
center (居中顯示)
space-between (把剩餘寬度平均分配到各子元素之間的間隙,邊上不留空白)
space-around(把剩餘寬度平均分配到各子元素之間的間隙,邊上的空白部分寬度等於子元素之間間隙的一半)
- align-items
決定項目在副軸上如何對齊
取值:
flex-start (靠近副軸起始方向顯示)
flex-end (靠近副軸結束方向顯示)
center (居中顯示)
baseline (基線對其顯示)
stretch(佔滿整個容器的高度)
- align-content
同時設置主軸和副軸的對齊方式
取值:
flex-start | flex-end | center | space-between | space-around | stretch
flex元素屬性
- order
定義元素的排列順序。數值越小,排列越靠前,默認爲0。
- flex-grow
定義項目的放大比例,默認爲0,即如果存在剩餘空間,也不放大。
- flex-shrink
定義了項目的縮小比例,默認爲1,即如果空間不足,該項目將縮小。
- flex-basis
定義了在分配多餘空間之前,項目佔據的主軸空間(main size)。瀏覽器根據這個屬性,計算主軸是否有多餘空間。它的默認值爲auto,即項目的本來大小。
- flex
flex-grow, flex-shrink 和 flex-basis的簡寫,默認值爲0 1 auto。後兩個屬性可選。
```
6. align-self
允許單個項目有與其他項目不一樣的對齊方式,可覆蓋align-items屬性。默認值爲auto,表示繼承父元素的align-items屬性,如果沒有父元素,則等同於stretch。該屬性可能取6個值,除了auto,其他都與align-items屬性完全一致。
```
實現簡單的頭部高度固定,底部高度自適應;底部左側寬度固定,底部右側寬度自適應
<div class="container">
<div class="item1"></div>
<div class="item2">
<div class="item3"></div>
<div class="item4"></div>
</div>
</div>
.container{
display:flex;
flex-direction:column;
}
.item1{
height:50px;
}
.item2{
flex:1;
display:flex;
}
.item3{
width:200px;
}
.item4{
flex:1;
}
流行的UI框架中的Container 佈局容器都是使用flex佈局實現的;在處理屏幕寬度自適應時非常方便