CSS 实现水平垂直居中

使用绝对定位

在已经知道子元素的宽高的时候,子元素设置成绝对定位,top,left,right,bottom=0, margin = auto

.wrap{
  position: relative;
  width: 500px;
  height: 200px;
  border: 2px solid #000;
}
.wrap > .inner{
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100px;
  height: 100px;
  margin: auto;
  background: #000;
  color: #fff;
}

在线预览

使用 transform

设置 transform: translate(-50%, -50%)

.wrap{
  position: relative;
  width: 500px;
  height: 300px;
  border: 2px solid #000;
}
.wrap>.inner{
  position: absolute;
  top:50%;
  left: 50%;
  border: 1px solid red;
  transform: translate(-50%, -50%);
}

在线预览

使用 flex

给父元素设置display:flex;justify-content:center;align-items:center;

.flex-container{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 400px;
  height: 400px;
  color: #fff;
  border: 5px solid green;
}
.flex-container > .flexitem{
  width: 100px;
  height: 100px;
  background-color: blue;
  border: 1px solid yellow
}

在线预览

附加 屏幕居中

.center-center{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100px;
  height: 100px;
  margin: auto;
  border: 1px solid red;
  background: #000;
  color: #fff;
}

在线预览