假设有如下结构的代码:

  1. <div id="app">
  2. <div id="content"></div>
  3. </div>
#app {
  width: 100px;
  height: 100px;
  border: 1px solid red;
}
#content {
  width: 50px;
  height: 50px;
  background-color: red;
}

有多少种方法可以实现水平垂直居中:

flex布局

#app {
  display: flex;
  justify-content: center;
  align-items: center;
}

绝对定位+CSS3translate

#app {
  position: relative;
}
#content {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

相对定位+translateY+margin

 #content {
   position: relative;
   top:50%;
   transform:translateY(-50%);
   background-color: red;
   margin: 0 auto;
}

绝对定位+margin

content如果没有设置高度或者没有会自动最大尺寸,绝对定位的值只要设置成相等即可,不一定非要0

#app {
  position: relative;
}
#content {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

相对定位+translate

#app {
  position: relative;
}
#content {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}