CSS 垂直居中

182 阅读2分钟

这里是个人对于 CSS 垂直居中的一些方法总结。

默认的HTML部分如下:

<div class="parent">      
  <div class="child">
    内容内容内容内容内容
    内容内容内容内容内容
    内容内容内容内容内容
  </div>      
</div>

:after、:before & inline-block & height & vertical-align

这个方法可以看作是 :after:before 前后夹住 div.child 来实现的垂直居中。代码如下:

.parent{
    height: 100px;
    text-align: center;  /* 水平居中 */
}
.parent:before{
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.parent:after{
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.child{
    width: 200px;
    display: inline-block;
    vertical-align: middle;    
}

absolute & top、负margin-top

.parent {
  height: 300px;
  position: relative;
}
div.child {
  height: 100px;
  position: absolute;
  top: 50%;
  margin-top: -50px;
}

同理:水平居中就用 left 和 负margin-left 。

absolute & top、translate -50%

该方法与上一个方法相比,使用 负translate 而不是 负margin。

.parent {
  height: 400px;
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

absolute & margin:auto

.parent {
  height: 400px;
  position: relative;
}
.child {
  height: 200px;
  width: 200px;
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

display:table 、table-cell & vertical-align

html 部分:

<div class="table">
  <div class="td">
    <div class="child">
      内容内容内容内容内容
      内容内容内容内容内容
      内容内容内容内容内容
    </div>
  </div>
</div>

css 部分:

div.table{
    height: 400px;
    display: table;
}
div.td{
    display: table-cell;
    vertical-align: middle;
}

flex & align-items

.parent {
  height: 400px;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

justify-content 属性定义项目在主轴上如何对齐,align-items 属性定义项目在交叉轴上如何对齐,flex-direction 属性可以决定主轴的方向,默认主轴是横轴。

grid & align-content

.parent {
  height: 400px;
  display: grid;
  align-content: center;/* 垂直居中 */
  justify-content: center;/* 水平居中 */
}

align-content、justify-content 属性是设置整个内容区域在容器里面的位置。justify-items、align-items 属性是设置单元格内容的位置.

flex & margin:auto

.parent {
  height: 400px;
  display: flex;
}
.child {
  margin: auto;
}

grid & margin:auto

.parent {
  height: 400px;
  display: grid;
}
.child {
  margin: auto;
}