元素水平垂直居中
Hkc 2018-02-25  css
html 代码:
<div class="box border">
  <div class="content"></div>
</div>
# 使用 flex 布局达到垂直居中的效果,少数旧浏览器可能不兼容。
.box {
  display: flex;
  height: 600px;
  width: 600px;
  border: 1px solid #000;
  align-items: center;
  justify-content: center;
}
.content {
  width: 300px;
  height: 300px;
  background: red;
}
# 使用相对定位和绝对定位以及 margin 值来实现元素的水平垂直居中
.box {
  height: 600px;
  width: 600px;
  border: 1px solid #cccccc;
  position: relative;
}
.content {
  position: absolute;
  width: 300px;
  height: 300px;
  background: red;
  top: 50%;
  left: 50%;
  margin-left: -150px;
  margin-top: -150px;
}
# 使用绝对和相对定位
.box {
  height: 600px;
  width: 600px;
  border: 1px solid #cccccc;
  position: relative;
}
.content {
  position: absolute;
  width: 300px;
  height: 300px;
  background: red;
  margin: auto;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
# 单行元素字体垂直居中
 {
  text-align: center;
  line-height: 外层元素高度;
}