【CSS 基础】垂直居中

65 阅读1分钟

实现垂直居中是常见的需求,也是经常在面试中出现。
公共部分

<div class="parent">
    <div class="child"></div>
</div>
.parent {
  background-color: #323232;
  width: 400px;
  height: 200px;
}
.child {
  width: 100px;
  height: 100px;
  background-color: #FFCB91;
}

absolute + 负margin

.parent {
  position: relative;
}
.child {
  position: absolute;
  left: 50%;
  top: 50%;
  margin: -50px 0 0 -50px;
}

效果如下:
11.png

absolute + margin auto

.parent {
  position: relative;
}
.child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

absolute + calc

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: calc(50% - 50px);
  left: calc(50% - 50px);
}

absolute + transform

.parent {
  background-color: #323232;
  width: 400px;
  height: 200px;
  margin: 100px auto;
  position: relative;
}
.child {
  width: 100px;
  height: 100px;
  position: absolute;
  background-color: #FFCB91;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 50% 相对于自身 */
}

table-cell

.parent {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.child {
  display: inline-block;
}

flex

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

grid

grid属于较新的特性,可能有兼容性问题

.parent {
  display: grid;
}
.child {
  align-self: center;
  justify-self: center;
}