1、line-height
div{
height: 100px;
line-height:100px;
text-align:center;
}
2、display:table-cell
table-cell这个属性是在看head first 书的时候学习的,通过display 设置为table table-row table-cell,让元素以表格的样子显示。
.out{
display:table;
}
.inner{
display: table-cell;
vertical-align: middle;
}
3、CSS3的flex布局
div{
/*设置为伸缩容器*/
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
/*水平居中*/
-webkit-box-pack: center;/*旧版本*/
-moz-box-pack: center;/*旧版本*/
-ms-flex-pack:center;/*混合版本*/
-webkit-justify-content:center;/*新版本*/
justify-content: center;/*新版本*/
/*垂直居中*/
-webkit-box-align: center;/*旧版本*/
-moz-box-align: center;/*旧版本*/
-ms-flex-align: center;/*混合版本*/
-webkit-align-items: center;/*新版本*/
align-items: center;/*新版本*/
}
4、使用padding,这需要知道确定的高度
5、CSS3的transform来实现
.center-vertical{
position: relative;
top:50%;
transform:translateY(-50%);
}.center-horizontal{
position: relative;
left:50%;
transform:translateX(-50%);
}
5、纯CSS实现不固定大小div相对于body垂直居中效果
<!DOCTYPE html>
<html>
<head>
<title>纯CSS实现不固定大小div相对于body垂直居中效果</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
.lanrenzhijia {position: fixed;left: -100%;right:100%;top:0;bottom: 0;text-align: center;font-size: 0;}
.lanrenzhijia:after {content:"";display: inline-block;vertical-align: middle;height: 100%;width: 0;}
.content {display: inline-block; *display: inline; *zoom:1; vertical-align: middle;position: relative;right: -100%;background:#639A29;width:300px;height:300px;}
</style>
</head>
<body >
<div class="lanrenzhijia">
<div class="content"></div>
</div>
</body>
</html>