正常组件使用默认的属性时,只需要设置text-align属性为center即可,如下:
demo.wxml
<view class="test">测试</view>
demo.wxss
.test{background-color: aqua;text-align: center;}
效果图:
如果此时将view组件的高度加高(设置height属性为100rpx)会出现下面的情况,文字在水平方向上的正中心,而不在垂直方向的正中心。
解决方法如下,把文字单独放在一个text标签中,用view标签包裹,view标签设置为flex,通过设置align-items和justify-content属性实现居中效果。
demo.wxml
<view class="test"><text>测试</text></view>
demo.wxss
.test{background-color: aqua;height: 100rpx;display: flex;justify-content: center;align-items: center;}
效果图: