有2种方式设置一个容器的元素垂直居中:
- 第1种
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 向左向上平移自身宽高的50% */
}
- 第2种
.container {
position: fixed;
height: 100%;
width: 100%;
display:flex;
flex-direction:row;
align-items:center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
Demo:
wxml:
<view class="horizontal-vertical-container-2">
<view class="test-item-container">
<view class="demo-text-1">A</view>
<view class="demo-text-2">B</view>
<view class="demo-text-3">C</view>
</view>
<view class="demo-text-4,demo-text-size">D</view>
<view class="demo-text-5,demo-text-size">E</view>
</view>
wcss:
page {
background-color: lightgreen;
height: 100%;
}
.horizontal-vertical-container-1 {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: lightcoral;
}
.horizontal-vertical-container-2 {
position: fixed;
height: 100%;
width: 100%;
display:flex;
flex-direction:row;
align-items:center;/*垂直居中*/
justify-content: center;/*水平居中*/
background-color: lightskyblue;
}
.test-item-container {
background-color: red;
width: 250rpx;
height: 250rpx;
}
.demo-text-1 {
background: rgba(26, 173, 25, 0.7);
}
.demo-text-2 {
background: rgba(39, 130, 215, 0.7);
}
.demo-text-3 {
background: rgba(255, 255, 255, 0.7);
}
.demo-text-4 {
background: rgba(110, 125, 255, 0.7);
}
.demo-text-5 {
background: rgba(125, 255, 255, 0.7);
}
.demo-text-size {
width: 120rpx;
height: 120rpx;
}
json:
{
"usingComponents": {},
"navigationStyle": "custom"
}
效果图: