于是,W3C 提出了一種新的方案----Flex 布局,可以簡(jiǎn)便、完整、響應(yīng)式地實(shí)現(xiàn)各種頁(yè)面布局。目前,它已經(jīng)得到了所有瀏覽器的支持,這意味著,現(xiàn)在就能很安全地使用這項(xiàng)功能,本人在微信小程序頁(yè)面中嘗試了一下彈性布局,個(gè)人感覺是:簡(jiǎn)直太好用了。
Flex 是 Flexible Box 的縮寫,意為"彈性布局",用來(lái)為盒狀模型提供最大的靈活性。
任何一個(gè)容器都可以指定為 Flex 布局。
.box{
display: flex;
}
復(fù)制代碼
不過(guò)需要注意一點(diǎn),就是設(shè)為 Flex 布局以后,子元素的float、clear和vertical-align屬性將失效。也就是說(shuō)浮動(dòng)布局和彈性布局不可共存,二者必居其一。
其實(shí)flex布局原理很簡(jiǎn)單,采用 Flex 布局的元素,稱為 Flex 容器(flex container),簡(jiǎn)稱"容器"。它的所有子元素自動(dòng)成為容器成員,稱為 Flex 項(xiàng)目(flex item),簡(jiǎn)稱"項(xiàng)目"。
容器默認(rèn)存在兩根軸:水平的主軸(main axis)和垂直的交叉軸(cross axis)。主軸的開始位置(與邊框的交叉點(diǎn))叫做main start,結(jié)束位置叫做main end;交叉軸的開始位置叫做cross start,結(jié)束位置叫做cross end。
項(xiàng)目默認(rèn)沿主軸排列。單個(gè)項(xiàng)目占據(jù)的主軸空間叫做main size,占據(jù)的交叉軸空間叫做cross size。
彈性布局的容器可以設(shè)置下面這些屬性:
flex-direction
flex-direction屬性決定主軸的方向(即項(xiàng)目的排列方向)。
.box {
flex-direction: row | row-reverse | column | column-reverse;
}
flex-wrap
默認(rèn)情況下,項(xiàng)目都排在一條線(又稱"軸線")上。flex-wrap屬性定義,如果一條軸線排不下,如何換行。
.box{
flex-wrap: nowrap | wrap | wrap-reverse;
}
flex-flow
flex-flow屬性是flex-direction屬性和flex-wrap屬性的簡(jiǎn)寫形式,默認(rèn)值為row nowrap。
.box {
flex-flow: <flex-direction> || <flex-wrap>;
}
justify-content
justify-content屬性定義了項(xiàng)目在主軸上的對(duì)齊方式。
.box {
justify-content: flex-start | flex-end | center | space-between | space-around;
}
align-items
align-items屬性定義項(xiàng)目在交叉軸上如何對(duì)齊。
.box {
align-items: flex-start | flex-end | center | baseline | stretch;
}
align-content
align-content屬性定義了多根軸線的對(duì)齊方式。如果項(xiàng)目只有一根軸線,該屬性不起作用。
.box {
align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}
復(fù)制代碼
說(shuō)了這么多,都是理論,我們來(lái)用彈性布局實(shí)戰(zhàn)一下,比如我們要模仿瑞辛咖啡小程序中的,首行單列,換行雙列,并且自適應(yīng)整個(gè)手機(jī)頁(yè)面的布局
頁(yè)面部分:
<template>
<div class="container1">
<div class="item11">
1
</div>
<div class="item12">
<div class="item1">
3
</div>
<div class="item1">
3
</div>
</div>
<div class="item12">
<div class="item1">
3
</div>
<div class="item1">
3
</div>
</div>
</div>
</template>
復(fù)制代碼
css部分:
.container1{
height: 100%;
width:100%;
background-color:beige;
display:flex;
flex-flow:column;
}
.item11{
height:300rpx;
background-color:cyan;
border: 1px solid #fff
}
.item12{
height:300rpx;
background-color:cyan;
border: 1px solid #fff;
display:flex;
}
.item1{
height:300rpx;
width: 50%;
background-color:cyan;
border: 1px solid #fff
}
復(fù)制代碼
輕松搞定,代碼量比浮動(dòng)布局少了很多,簡(jiǎn)直完美。