用inline-block和vertical-align,通過行內塊級元素的方式實現全屏居中;
利用:before偽類選擇器,模擬一個虛擬行內塊級元素;
行內塊級元素換行會產生間隙,這個間隙跟font-size的大小有關,so在居中的時候需要利用margin負邊距的方式去掉間隙;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>居中</title>
<style type="text/css">
body {
margin:0;
_height:100%; /*兼容IE6*/
}
.container {
width: 100%;
height: 100%;
/*100%全屏需要使用定位*/
position: absolute;
top: 0;
left: 0;
/*使行內元素或者行內塊級元素水平居中*/
text-align: center;
background-color: #ccc;
}
.container:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
.center-p {
background-color: yellow;
display: inline-block;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="container">
<div class="center-p">
table-cell居中
</div>
</div>
</body>
</html>