flex布局簡介
微信小程序頁面布局方式采用的是Flex布局。Flex布局,是W3c在2009年提出的一種新的方案,可以簡便,完整,響應式的實現各種頁面布局。
Flex布局提供了元素在容器中的對齊,方向以及順序,甚至他們可以是動態的或者不確定的大小的。
樣式設置為
display:flex:
采用 Flex 布局的元素,稱為 Flex 容器(flex container),簡稱"容器"
容器默認有兩個軸:主軸(main axis)和側軸(cross axis)。
主軸的開始位置為主軸起點(main start),主軸的結束位置為主軸終點(main end),而主軸的長度為主軸長度(main size)。
同理側軸的起點為側軸起點(cross start),結束位置為側軸終點(cross end),長度為側軸長度(cross size)。詳情見下圖:
flex布局的屬性
1.flex-direction
主軸的方向使用flex-direction屬性控制,主軸並不是一定是從左到右的,同理側軸也不一定是從上到下,它有4個可選值:
row(默認值):主軸為水平方向,起點在左端。 row-reverse:主軸為水平方向,起點在右端。 column:主軸為垂直方向,起點在上沿。 column-reverse:主軸為垂直方向,起點在下沿

2.justify-content屬性
定義了子元素在主軸上的對齊方式。
flex-start 主軸起點對齊(默認值) flex-end 主軸結束點對齊 center 在主軸中居中對齊 space-between 兩端對齊,除了兩端的子元素分別靠向兩端的容器之外,其他子元素之間的間隔都相等 space-around 每個子元素之間的距離相等,兩端的子元素距離容器的距離也和其它子元素之間的距離相同。

3. align-items屬性
表示側軸上的對齊方式
stretch 填充整個容器(默認值) flex-start 側軸的起點對齊 flex-end 側軸的終點對齊 center 在側軸中居中對齊 baseline 以子元素的第一行文字對齊

舉例:

wxml
<!--pages/my/my.wxml--> <view class="menu"> <view class="item"> <text class="c1">我的頭像</text> <image src="/images/hg.jpg" class="my-avatar"></image> </view> <view class="item"> <text class="c1">我的頭像</text> <image src="/images/hg.jpg" class="my-avatar"></image> </view> <view class="item"> <text class="c1">我的頭像</text> <image src="/images/hg.jpg" class="my-avatar"></image> </view> </view> <view>示例3</view> <view class="auction"> <view class="items"> <text class="title">第一場 紫砂壺專場</text> <view class="tips"> <view class="status">2020-01-01</view> <view class="count">111次圍觀</view> </view> <image src="/images/hh.png" class="big" mode="aspectFill"></image> <view class="small"> <image src="/images/hg.jpg" class="my-avatar"></image> <image src="/images/hg.jpg" class="my-avatar"></image> <image src="/images/hg.jpg" class="my-avatar"></image> <image src="/images/hg.jpg" class="my-avatar"></image> </view> </view> </view>
wxss
/* pages/my/my.wxss */ .menu{ display: flex; flex-direction: row; /*規則主軸方向*/ align-items: flex-start; /*副軸方向排列*/ justify-content: space-around; /*主軸方向排列*/ border: 2rpx solid #ddd; height: 200rpx } .my-avatar{ width: 128rpx; height: 128rpx; margin: 20rpx; border-radius: 50%; } .c1{ color: red } .menu .item{ display: flex; flex-direction: column; align-items: center; /*副軸方向排列*/ } .auction .items { display: flex; flex-direction: column; } .auction .items .title{ font-size: 48rpx; font-weight: 500; } .auction .items .tips{ display: flex; flex-direction: row; margin: 10rpx; justify-content: space-between; font-size: 30rpx; color: #8c8c8c; } .auction .items .big{ width:100%; height: 400rpx; border-bottom: 1px solid #eee; } .auction .items .small{ display: flex; flex-direction: row; }
