微信小程序之flex布局
在微信小程序中,view是最基础的布局容器,其支持两种布局方式block
、flex
,默认情况下,view的布局方式是block
,如下所示:
<view>
<view style='background:red;'>1</view>
<view style='background:blue;'>2</view>
<view style='background:yellow;'>3</view>
</view>
效果图:
flex布局
flex-direction
在给view设置属性display: flex;
之后,view的布局方式就会变为flex
模式,此外还需要设置其flex-direction
控制布局方向,flex-direction
有4个值:
- row:从左到右的水平方向为主轴
- row-reverse:从右到左的水平方向为主轴
- column:从上到下的垂直方向为主轴
- column-reverse:从下到上的垂直方向为主轴
flex-direction: row;
<view class='flex'>
<view class='flex-item' style='background:red;'>1</view>
<view class='flex-item' style='background:blue;'>2</view>
<view class='flex-item' style='background:yellow;'>3</view>
</view>
.flex {
display: flex;
flex-direction: row;
background: lightgray
}
.flex-item {
width: 60px;
}
效果图:
flex-direction: row-reverse
效果图:
flex-direction: column
效果图:
flex-direction: column-reverse
效果图:
justify-content
设置完view的布局方向之后,想要控制内容的对齐方式,需要设置justify-content
属性,该属性值有:
- flex-start:主轴起点对齐(默认值)。
- flex-end:主轴终点对齐。
- center:在主轴中居中对齐。
- space-between:两端对齐,除了两端的子元素分别靠向两端的容器之外,其他子元素之间的间隔都相等。
- space-around:每个子元素之间的距离相等,两端的子元素距离容器的距离也和其它子元素之间的距离相同。
flex-start
<view class='flex'>
<view class='flex-item' style='background:red;'>1</view>
<view class='flex-item' style='background:blue;'>2</view>
<view class='flex-item' style='background:yellow;'>3</view>
</view>
.flex {
display: flex;
flex-direction: row;
justify-content: flex-start;
background: lightgray
}
.flex-item {
width: 60px;
}
效果图:
flex-end
效果图:
center
效果图:
space-between
效果图:
space_around
align-items
align-items
属性值有:
- stretch 填充整个容器(默认值)
- flex-start 起点对齐
- flex-end 终点对齐
- center 居中对齐
- baseline 以子元素的第一行文字对齐
flex-start
<view class='flex'>
<view class='flex-item' style='background:red; height:50px;'>1</view>
<view class='flex-item' style='background:blue; height:70px;'>2</view>
<view class='flex-item' style='background:yellow;height:90px;'>3</view>
</view>
.flex {
display: flex;
flex-direction: row;
background: lightgray;
justify-content: space-around;
align-items: baseline;
height: 100px;
}
.flex-item {
width: 60px;
}
效果图:
flex-end
效果图:
center
效果图:
baseline
效果图:
子 View 还有个属性 align-self,可以覆盖父元素的 align-items 属性,它有6个值可选:auto | flex-start | flex-end | center | baseline | stretch (auto 为继承父元素 align-items 属性,其他和 align-items 一致)
此外还有 flex-wrap 属性,用于控制子 View 是否换行,有3个值可选:
- nowrap:不换行(默认)
- wrap:换行
- wrap-reverse:换行,第一行在最下面
子 View 有个 order 属性,可以控制子元素的排列顺序,默认为0。