纯CSS实现垂直居中的几种方法

方法一:以毒攻毒!用 IE 的 bug 解决 IE 中的绝对居中,嵌套三层div

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .middle-demo-4{
            height: 300px;
            background-color: bisque;
            position: relative;
        }
        .middle-demo-4 div{
            position: absolute;
            top: 50%;
            left: 0;
        }
        .middle-demo-4 div div{
            position: relative;
            top: -50%;
            left: 0;
        }
        .text{
            background-color: darkkhaki;
        }
    </style>
</head>
<body>
    <div class="middle-demo-4">
        <div>
            <div class="text">
                好地方军所扩付或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或       
            </div>
        </div>
    </div>
</body>
</html>

方法二:只有一行内容,使用table-cell


<div class="box box1">
        <span>垂直居中</span>
</div>

.box1{
    display: table-cell;
    vertical-align: middle;
    text-align: center;        
}

方法三:display:flex

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

方法四:绝对定位和负边距

   .box3{position:relative;}
.box3 span{
   position: absolute;
   100px;
   height: 50px;
   top:50%;
   left:50%;
   margin-left:-50px;
   margin-top:-25px;
   text-align: center;
}

方法五:绝对定位和0

.box4 span{
   50%; 
  height: 50%; 
  background: #000;
  overflow: auto; 
  margin: auto; 
  position: absolute; 
  top: 0; left: 0; bottom: 0; right: 0; 
}

这种方法跟上面的有些类似,但是这里是通过margin:auto和top,left,right,bottom都设置为0实现居中,很神奇吧。不过这里得确定内部元素的高度,可以用百分比,比较适合移动端。

方法六:translate

.box6 span{
  position: absolute;
  top:50%;
  left:50%;
  100%;
  transform:translate(-50%,-50%);
  text-align: center;
}
原文地址:https://www.cnblogs.com/web-record/p/9144874.html