1.初始化我們的布局
.userContainer {
background-color: darkgreen;
width: 100%;
height: 100%;
}
.user-item {
background-color: red;
width: 120rpx;
height: 120rpx;
border: 1px solid black;
}
<!--pages/user/user.wxml-->
<view class="userContainer">
<view class="user-item">1</view>
<view class="user-item">2</view>
<view class="user-item">3</view>
<view class="user-item">4</view>
<view class="user-item">5</view>
</view>
默認的顯示效果如下:
image.png
2.現在我們使用flex布局:
.userContainer {
background-color: darkgreen;
width: 100%;
height: 100%;
display: flex;
}
image.png
flex容器的屬性
flex-direction的使用(決定元素的排列方向):
flex-direction共有四個值,分別為row,row-reverse,column,column-reverse.其中row為默認值.
-
row-reverse:
row-reverse.png -
column:
column.png -
column-reverse:
column-reverse.png
flex-wrap(決定元素在排列不下的時候如何換行):
共有3個常用值,nowrap,wrap, wrap-reverse.其中nowrap為默認值.
-
nowrap,元素放不下時會被強行拉伸:
image.png -
wrap,元素排列不下,自動換行:
image.png - wrap-reverse,反向排列:
image.png
flex-flow是flex-direction和flex-wrap的合寫:
flex-flow: row wrap;
justify-content(決定元素在主軸的對齊方式):
共有6個常用屬性,flex-start,flex-end,center,space-between,space-around,space-evently.其中,flex-start為默認值:
-
flex-start:
image.png -
flex-end:
image.png -
center:
image.png -
space-between:
image.png -
space-around:
image.png -
space-evenly:
image.png
align-items(元素在側軸的對齊方式):
共有5種常用屬性,stretch,center,flex-start,flex-end,baseline.其中stretch為默認屬性.
-
stretch(如果只是指定寬度,而沒有指定高度):
image.png -
flex-start(指定了寬高):
image.png flex-end(指定了寬高):
image.png
- baseline(子元素中首行文字對齊):
image.png
flex 元素屬性的使用
flex-grow(當有多余空間時,元素的放大比例)
默認值為0,表示不會擴大.設置的其他值表示 該元素占據所剩下空間的比例
.user-item {
background-color: red;
width: 100rpx;
height: 100rpx;
border: 1px solid black;
flex-grow: 1;
}
.tree {
display: flex;
align-items: flex-end;
flex-grow: 2;
}
image.png
flex-shrink(當空間不足時,元素的縮放比例)
默認是1,表示當空間不足時,默認等比縮小.如果想讓其中某個元素不縮小,那么可以將其值更改為0.
.user-item {
background-color: red;
width: 250rpx;
height: 250rpx;
border: 1px solid black;
/* 默認按比例縮放 */
flex-shrink: 1;
}
.tree {
display: flex;
align-items: flex-end;
/* 不縮小該元素 */
flex-shrink: 0;
}
image.png
flex-basis(元素在主軸上占據的空間)
.user-item {
background-color: red;
width: 200rpx;
height: 200rpx;
border: 1px solid black;
}
.tree {
display: flex;
align-items: flex-end;
flex-basis: 300rpx;
}
image.png
flex是grow shink basis的簡寫
.user-item {
background-color: red;
width: 200rpx;
height: 200rpx;
border: 1px solid black;
/* 80會覆蓋掉width的200 */
flex: 0 1 80rpx;
}
image.png
order 元素的排列順序
<view class="userContainer">
<view class="user-item" style="order: 3">1</view>
<view class="user-item" style="order: 4">2</view>
<view class="user-item three" style="order: 1">3</view>
<view class="user-item" style="order: 2">4</view>
</view>
image.png
align-self(設置自身的對齊方式)
.user-item {
background-color: red;
width: 200rpx;
height: 200rpx;
border: 1px solid black;
/* 設置自身的對齊方式*/
align-self: flex-end;
}
.three {
display: flex;
align-items: flex-end;
/* 設置自身的對齊方式*/
align-self: center;
}