Css实现盒子在网页内垂直居中的常用方式

542 阅读1分钟
  1. 定位法+margin(知道盒子实际宽高)
.parent {
  position: relative;
  width: 100%;
  height: 100vh;
}
.box {
  width: 100px;
  height: 100px;
  background: blueviolet;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: -50px;
  margin-left: -50px;
}

2.定位+transform(无需知道盒子实际宽高)

.parent {
  position: relative;
  width: 100%;
  height: 100vh;
}
.box {
  width: 100px;
  height: 100px;
  background: blueviolet;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%); 
}

3.flex布局(父元素)

body {
  position: relative;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.box {
  width: 100px;
  height: 100px;
  background: blueviolet;
}

4.display: table-cell 无兼容性问题

.box {
  width: 100px;
  height: 100px;
  background: blueviolet;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

image.png

以上四种方式 都可以实现盒子水平居中 具体使用哪一种根据实际情况决定