在開發(fā)微信小程序UI時(shí),安卓一個(gè)很簡(jiǎn)單的cardview內(nèi)容居中效果,在微信小程序布局時(shí)寫的比較復(fù)雜,這里記錄一下:
想實(shí)現(xiàn)如下圖這樣一個(gè)效果中,每個(gè)item的圖表和文字居中顯示,怎么實(shí)現(xiàn)呢?

image.png
index.wxml中代碼如下:
<view class="items">
<navigator url="/pages/banner/banner" hover-class="navigator-hover" class="plate-item">
<view class="item">
<image src="{{bannerLogoUrl}}"></image>
<text class="title">輪播圖</text>
</view>
</navigator>
<navigator url="/pages/button/button" hover-class="navigator-hover" class="plate-item">
<view class="item">
<image src="{{buttonLogoUrl}}"></image>
<text class="title">按鈕</text>
</view>
</navigator>
<navigator url="/pages/dialog/dialog" hover-class="navigator-hover" class="plate-item">
<view class="item">
<image src="{{dialogLogoUrl}}"></image>
<text class="title">對(duì)話框</text>
</view>
</navigator>
</view>
index.js中定義data,設(shè)置圖標(biāo)地址:
Page({
data:{
bannerLogoUrl:'/resources/ic_widget_banner.png',
buttonLogoUrl:'/resources/ic_widget_button.png',
dialogLogoUrl:'/resources/ic_widget_dialog.png'
}
})
index.wxss的樣式代碼如下:
.items{
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.plate-item{
width: 33%;
height: 100px;
}
.item{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
border-color: chartreuse;
border-width: 1px;
background-color: red;
}
.item image{
width: 30px;
height: 30px;
}
.title{
margin-top: 10px;
}
每個(gè)item中內(nèi)容居中的關(guān)鍵樣式代碼是:
.item{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
border-color: chartreuse;
border-width: 1px;
background-color: red;
}
display:block
小程序的3個(gè)視圖容器(view,srcoll-view,swiper)默認(rèn)值均為display:block
block表示[塊內(nèi)]容器模式,總是使用新行開始顯示
display:flex

image.png
- flex-direction屬性,有下面4個(gè)可選值,默認(rèn)為row
- row:水平排列 (默認(rèn))
- row-reverse:水平翻轉(zhuǎn)排列
- column:豎直排列
- column-reverse:豎直翻轉(zhuǎn)排列
flex屬性值,自動(dòng)調(diào)整各個(gè)子組件的寬度,一行排不開會(huì)被壓縮
如果不想被壓縮,就要用到另一個(gè)屬性flex-wrap,它有3個(gè)屬性值:
- nowrap(不換行,默認(rèn)值)
- wrap(換行)
- wrap-reverse(與wrap的效果相反)
對(duì)齊方式:align-items和justify-content
只有在display:flex時(shí)對(duì)齊方式才起作用,如果是display:block則不起作用。
-
align-items,子組件在側(cè)軸(豎直)方向上的對(duì)齊方式
- center,側(cè)軸居中(在父組件寬度/高度上的居中,并不是屏幕寬度/高度居中)
- flex-start,側(cè)軸起始點(diǎn)開始
- flex-end,側(cè)軸終點(diǎn)開始
- baseline,效果不明
- stretch,效果不明
-
justify-content,子組件在主軸(水平)方向上的對(duì)齊方式
- center,主軸方向居中(在父組件高度/寬度上的居中,并不是屏幕高度/看寬度居中)
- flex-start,主軸起始點(diǎn)對(duì)齊
- flex-end,主軸結(jié)束點(diǎn)對(duì)齊
- space-between,兩端對(duì)齊,除了兩端的子元素分別靠向兩端的容器外,其余子元素之間的間隔都相等。
- space-around,子元素之間的距離相等,兩端子元素距離容器的距離是其它子元素之間的距離的1/2。
- space-evenly,子元素之間的距離相等,兩端子元素距離容器的距離和其它子元素之間的距離相同。
display:none
控制view組件的顯示或隱藏值,還有一個(gè)屬性visibility的hidden值,也能讓控件消失,但卻會(huì)占位置,有一個(gè)空白位置,display:none會(huì)讓組件消失,后面的組件占用他的位置。

image.png