小程序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:


  
    A
    B
    C
  
  D
  E

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的效果图

你可能感兴趣的:(小程序css设置垂直居中显示)