您的位置:首页 > Web前端 > CSS

纯CSS实现容器基于窗口垂直居中(仅支持IE8+及现代浏览器)

2013-06-29 00:00 531 查看
1. 方法1:

<!DOCTYPE html>
<html>
<head>
<title>基于窗口垂直居中 by  司徒正美</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<style>
body{
background-image:url(about:blank); /* for IE6 */
}

.fixed{
position: fixed;
left: 50%;
top:50%;
height: 0;/* 不占据位置 */
background-color: red;
}

.relative{
position: relative;
left: -50%;/*处理水平方向 */
/*处理垂直方向*/
-webkit-transform: translateY(-50%) translateZ(0);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%) translateZ(0);

background-color: pink;
}

.content{
padding:80px;
background-color: lightblue;

}

</style>

</head>
<body >
<h1<基于窗口垂直居中 by  司徒正美</h1>
<button onclick="document.getElementById('dialog').style.display = 'block'">open</button>

<div class="fixed" id="dialog">
<div class="relative">
<div class="content">
<button style='position: absolute;right:0;top:0' type='button' onclick="document.getElementById('dialog').style.display = 'none'">close</button>
XXXXXXXXXXXXXXXXX
</div>
</div>
</div>

</body>
</html>


2. 方法2:

<!DOCTYPE html>
<html>
<head>
<title>基于窗口垂直居中 by  司徒正美</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<style>
body{
background-image:url(about:blank); /* for IE6 */
}

.fixed{
position: fixed;
left: -100%;
right:100%;
top:0;
bottom: 0;
background-color: #CCC;
text-align: center;
font-size: 0;
}
.fixed:after {
content:"";
display: inline-block;
vertical-align: middle;
height: 100%;
width: 0;
}

.content{
display: inline-block;
*display: inline;
*zoom:1;
vertical-align: middle;
text-align: left;
position: relative;
right: -100%;
font-size: 16px;
background-color: lightgreen;
width:150px;
height: 150px;
}

</style>

</head>
<body >
<button onclick="document.getElementById('dialog').style.display = 'block'">open</button>
<h1>基于窗口垂直居中 2 by  司徒正美</h1>
<div class="fixed" id="dialog">

<div class="content">
<button style='position: absolute;right:0;top:0' type='button' onclick="document.getElementById('dialog').style.display = 'none'">close</button>
XXXXXXXXXXXXXXXXX
</div>

</div>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐