标签:
随着接触的项目越来越多,就可以感受到“居中”应用的非常广泛。
水平居中,这里就不多说了,margin:0 auto就可以解决。
最令人烦恼的是垂直居中,这也是本章将重点总结的地方。
下面按类来划分垂直居中的解决方法:
1.单行文本垂直居中
代码:
div p{ line-height: 30px; height: 30px; }
2.图片居中
<div> <img src="1.jpg" alt="" /> </div>
div{ width:300px; border:1px solid red; line-height: 300px;/*重点*/ } div img{ width: 100px; height: 100px; vertical-align: middle;/*重点*/ }
3.表格垂直居中
<div> <p>this is content</p> </div>
div{ display: table; border: 1px solid red; height: 100px; width: 300px; } div p{ display: table-cell; vertical-align: middle; }
4.块级元素垂直居中
<div class="blue"> <div class="red"></div> </div>
.blue{ width: 200px; height: 200px; position: relative; background-color: blue; } .red{ width: 100px; height: 30%; position: absolute; top: 50%; margin-top:-15%; /*margin-top是height的一半*/ background-color: red; }
另一种样式写法
.blue{ width: 200px; height: 200px; position: relative; /*重点*/ background-color: blue; } .red{ width: 100px; height: 30%; position: absolute;/*重点*/ top: 0;/*重点*/ bottom: 0;/*重点*/ margin:auto;/*重点*/ background-color: red; }
5.借助空div使容器垂直居中
<div class="blue"> <div class="floater"></div> <div class="red"></div> </div>
.blue{ height: 200px; width: 200px; background-color: blue; } .red{ clear: both; height: 100px; background-color: red; } .floater{ float: left; height: 50%; width: 100%; margin-bottom: -50px;/*内容高度的一半*/ }
6.利用css3实现垂直居中
该中方法IE不兼容
<div class="blue"> <div class="red"></div> </div>
.blue{ width: 300px; height: 200px; display: -webkit-box; /*重点*/ -webkit-box-align:center;/*重点*/ background-color: blue; } .red{ width: 100px; height: 100px; background-color: red; }
标签:
原文地址:http://www.cnblogs.com/Imever/p/4721116.html