微信小程序 View 支持两种布局方式:Block 和 Flex
所有 View 默认都是 block
要使用 flex 布局的话需要显式的声明:
display:flex;
下面就来介绍下微信小程序的 Flex 布局
1.先做一个简单的 demo
<view class="main">
<view class="item item1">1</view>
<view class="item item2">2</view>
<view class="item item3">3</view>
</view>
2.加上背景色能看的更清楚些
.main{
width:100%;
background-color:antiquewhite;
}
.item{
height:100rpx;
width:100rpx;
}
.item1{
background-color:red;
}
.item2{
background-color:dodgerblue;
}
.item3{
background-color:greenyellow;
}

然后我们先都加上 display: flex
好使用 flex 布局,主意,貌似 view 不会自动继承,需要在每个想使用的 view 里都加上。
首先是横向布局和竖向布局,要设置属性 flex-direction ,它有4个可选值:
row:从左到右的水平方向为主轴
row-reverse:从右到左的水平方向为主轴
column:从上到下的垂直方向为主轴
column-reverse:从下到上的垂直方向为主轴
我们来看下设置 row 和 row-reverse 的区别:


然后我们要设置元素在横向上的布局方向,需要设置 justify-content 属性,它有5个值可选:





然后我们要设置元素在纵向上的布局方向,需要设置 align-items 属性,它有5个值可选:





子 View 还有个属性 align-self,可以覆盖父元素的 align-items 属性,它有6个值可选:auto | flex-start | flex-end | center | baseline | stretch (auto 为继承父元素 align-items 属性,其他和 align-items 一致)
比如上面最后一个 baseline 的例子,我们把 item3 设置 align-self:flex-end;
就成了这个样子:

此外还有 flex-wrap 属性,用于控制子 View 是否换行,有3个值可选:
nowrap:不换行(默认)
wrap:换行
wrap-reverse:换行,第一行在最下面
还有子 View 有个 order 属性,可以控制子元素的排列顺序,默认为0。
比如还是上面那个例子,我们把 item3 设置 order:-1; 可以把 item3 排在前面

flex 常用布局就这些
网友评论