最近遇到好多垂直居中的问题,特地来这里总结一下,同时也方便大家查阅,废话不多说,走起~
实现这种效果
1.方法一,margin auto
<span style="font-family:Microsoft YaHei;font-size:14px;"><html>
<head>
<meta charset="utf-8"/>
<style>
.wrap{
border: 2px solid red;
position: relative;
height: 400px;
width: 400px;
}
.inner{
background-color: darkseagreen;
height: 150px;
width: 150px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="wrap">
<div class="inner"></div>
</div>
</body>
</html></span>
2.方法二,负的margin
同样的html结构 ,不同的css
<style>
.wrap{
border: 2px solid red;
position: relative;
height: 400px;
width: 400px;
}
.inner{
background-color: darkseagreen;
height: 150px;
width: 150px;
position: absolute;
margin: auto;
top: 50%;
left: 0;
right: 0;
margin-top: -75px;
}
</style>
说明:父元素也是要求有固定高度,将top值设置为50%,将margin-top设置为inner Div 高度的一半。
3.方法三 加:after
<style>
.wrap{
border: 2px solid red;
width: 400px;
height: 392px;
text-align: center;
}
.wrap:after{
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
.inner{
background-color: darkseagreen;
height: 150px;
width: 150px;
display: inline-block;
vertical-align: middle;
}
</style>
4. 方法四 transform
<style>
.wrap{
border: 2px solid red;
width: 400px;
height: 392px;
position: relative;
}
.inner{
background-color: darkseagreen;
height: 150px;
width: 150px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
这种方式也是可以的,transform 记得加 -webkit-
其实还有好多别的方法,不太接地气.... 就不说了。