Skip to content

Latest commit

 

History

History
178 lines (169 loc) · 2.59 KB

垂直居中.md

File metadata and controls

178 lines (169 loc) · 2.59 KB

垂直居中的方式

设定行高

  • 方法:将内层元素设置为行内元素,将外层元素line-height设置成高度一样的数值
  • 缺点:仅适用于单行的行内元素
.outer{
  width: 200px;
  height: 150px;
  line-height: 200px;
  text-align: center;
  border: 1px solid #000;
}
.inner{
  width: 30px;
  height: 30px;
  background: #c00;
  display: inline-block;
}

添加伪元素(::before、::after)

  • 缺点:仅适用于行内元素
.outer{
  width: 200px;
  height: 150px;
  text-align: center;
  border: 1px solid #000;
}
.inner1::before{
  content: '',
  width: 0;
  height:100%;
  display: inline-block;
  position: relative;
  vartical-align: middle;
  background: #f00;
}
.inner1{
  width: 30px;
  height: 30px;
  background: #c00;
  display: inline-block;
  vertical-align: middle;
}
.inner2{
  width: 30px;
  height: 60px;
  background: #0c0;
  display: inline-block;
  vertical-align: middle;
}
.inner3{
  width: 30px;
  height: 40px;
  background: #00f;
  display: inline-block;
  vertical-align: middle;
}

cal动态计算

父元素的50%减去子元素的50%

.outer{
  width: 150px;
  height: 100px;
  border: 1px solid #000;
}
.inner{
  position: relative;
  width: 50px;
  height: 50px;
  background: red;
  top: calc(50% - 25px);
  margin-left: calc(50% - 25px);
}

使用表格或假装表格

// HTML
<table>
  <tr>
    <td>
      <div>表格垂直居中</div>
    </td>
  </tr>
</table>
<div class="outer">
  <div class="inner">假的表格垂直居中</div>
</div>

// CSS
.outer{
  display: table-cell;
}
td, .outer{
  width: 150px;
  height: 100px;
  border: 1px solid #000;
  vertical-align: middle;
}
td div, .inner{
  width: 100px;
  height: 50px;
  margin: 0 auto;
  background: red;
}

transform

.outer{
  width: 200px;
  height: 200px;
  border: 1px solid #000;
}
.inner{
  position: relative;
  width: 100px;
  height: 50px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #095;
}

绝对定位

.outer{
  position: relative;
  width: 200px;
  height: 150px;
  border: 1px solid #000;
}
.inner{
  position: absolute;
  width: 100px;
  height: 50px;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  background: #f60;
}

flex

.outer{
  display: flex;
  align-items: center; // 垂直居中
  justify-content: center; // 水平居中
  width: 200px;
  height: 150px;
  border: 1px solid #000;
}
.inner{
  width: 100px;
  height: 100px;
  background: #099;
}

grid布局

.outer{
  display: grid;
}
.inner{
  justify-self: center;
  align-self: center;
}