面试经常会被问到这个问题,特地总结了下几种方法。
方法1:display: table
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>T</title>
<style>
html,body {margin:0; padding:0; height:100%;}
.a {margin:0 auto; width:800px; height:100%; display:table;}
.b {display:table-cell; vertical-align:middle;}
.c {background:#f11;}
p{height:20px;}
</style>
</head>
<body>
<div class="a">
<div class="b">
<div class="c">
<br><br><br><br><br><br><br>
<p></p>
</div>
</div>
</div>
</body>
</html>
方法2:定位+transform
.center {
position: fixed;
top: 50%;
left: 50%;
background-color: #000;
width:50%;
height: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
}
<div class="center"></div>
方法3:flex布局
.box{
display: flex;
justify-content: center;
align-items: center;
height:100px;
border:1px solid red;
}
来源:https://www.cnblogs.com/easonw/p/9210258.html