小程序css设置垂直居中显示

有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"
}

效果图:

使用horizontal-vertical-container-1的效果图

使用horizontal-vertical-container-2的效果图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容