七种方式实现垂直居中

783 阅读2分钟

如果 .parent 的 height 不写,只需要 padding: 10px 0; 就能将 .child 垂直居中; 如果 .parent 的 height 写死了,就很难把 .child 居中,以下是垂直居中的方法。

1. table自带功能

这是table的自带功能

2. 100% 高度的 afrer before 加上 inline block

这个方法还有一个优化版本,改成将after和after改成伪元素

.parent:before{
  content:'';
  outline: 3px solid red;
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
.parent:after{
  content:'';
  outline: 3px solid red;
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

3.div伪装成table

关键代码
display: table;
display: table-row;
display: table-cell;

4. margin-top:-(子元素的)50%

定位之后,margin-top设置为 -50% (子元素)

.child{
  border: 1px solid green;
  width: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -150px;
  height: 100px;
  margin-top: -50px;
}

5.translate -50%

<div class="parent">
    <div class="child">
      一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
    </div>
 </div>
 
 //-----------------css--------------------
 
 .parent{
  height: 600px;
  border: 1px solid red;
  position: relative;
}
.child{
  border: 1px solid green;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}

6.absolute margin auto

是通过定位的另一种方法

<div class="parent">
    <div class="child">
      一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
    </div>
</div>

//-----------------------css------------------------------

.parent{
  height: 600px;
  border: 1px solid red;
  position: relative;
}
.child{
  border: 1px solid green;
  position: absolute;
  width: 300px;
  height: 200px;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

7. flex

 <div class="parent">
    <div class="child">
      一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
    </div>
 </div>
 
 //---------------------css---------------------------
 
 .parent{
  height: 600px;
  border: 3px solid red;
  
  display: flex;                    //关键代码
  justify-content: center;          //关键代码
  align-items: center;              //关键代码
}
.child{
  border: 3px solid green;
  width: 300px;
}