转载自 http://www.cnblogs.com/dan-dan/p/4771614.html
一、负margin法
-
这是比较常用的方法,在知道元素的宽高的前提下才能使用
<div id="a"></div> #a{ height:300px; width:300px; position:absolute; top:50%; left:50%; margin-left:-150px; margin-top:-150px; }
负margin是个非常有意思的用法,深入了解后会发现他在布局上相当有用
优点:代码量少,兼容性好。
缺点:非响应式方法,内容可能会超出容器。
二、transform法
<div id="a"></div>
#a{
width: 50%;
height: 20%;
background: green;
position: absolute;
top:50%;
left: 50%;
transform:translate(-50%, -50%);
-webkit-transform:translate(-50%, -50%);
-ms-transform:translate(-50%, -50%);
}
- 优点:代码量少;宽高可变,相应式布局
- 缺点:不支持IE8,可能需要带供应商前缀
三、Flexbox法
<div class="vertical-container">
<div class="a"></div>
</div>
.vertical-container {
height: 300px;
width: 300px;
background: #ccc;
display: -webkit-flex;
display: flex;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
}
.a{
width: 200px;
height: 200px;
background: green;
}
- Flexbox的用法远不止如此,在布局上还有很多有趣的用法。
四、“完全水平垂直居中”:
-
必须要设置元素的高度,图片自身有高度的可以不设。
<div id="a"></div> #a{ width: 200px; height: 200px; background: red; margin:auto; position: absolute; top:0;left:0;right: 0;bottom: 0; }