目标:
除了最后一点,下面的例子已经实现了一切。
如何让这个div在窗口中垂直居中?即,我希望红色区域表现得像绿色区域,但只是垂直而不是水平。
(此设计旨在用于移动设备屏幕的响应式设计。尽可能不涉及 JS。)
<!doctype html>
<html>
<head>
<style>
body,html{
height:100%;
margin:0px;
background:green;
}
#t1{
position:relative;
height:100%;
max-width:640px;
margin:0 auto;
background-color:red;
}
#t1-1{
position:absolute;
height:100%;
max-height:640px;
width:100%;
background-color:#dddddd;
overflow:hidden;/*demo purpose*/
}
/*the following stuff are for demo only*/
img{
position:absolute;
opacity:0.5;
}
img.w{
width:100%;
}
img.h{
height:100%;
}
</style>
</head>
<body>
<div id="t1">
<div id="t1-1">
<img class="h" src="http://www.google.com/images/srpr/logo3w.png" />
<img class="w" src="http://www.google.com/images/srpr/logo3w.png" />
</div>
</div>
</body>
</html>
附言在这个例子中,一些桌面浏览器在内部为整个东西设置了一个最小宽度值(例如 Chrome 中的 400px),使 div 无法保持水平收缩。
您可能需要一些 javascript 才能使其工作:
首先,您需要一个 <div>
元素布局,所以我称之为mask:
<div id="mask"></div>
然后,将其样式化以填充整个文档,并给出 max-width
和 max-height
:
<style>
#mask {
position: fixed;
height: 100%;
max-height: 400px;
width: 100%;
max-width: 400px;
top: 0;
left: 0;
background: red;
}
</style>
此样式不执行居中 工作,因此您需要您的 javascript 来完成它,我们有一个 layoutMask
判断 div 是否居中的函数:
var mask = document.getElementById('mask');
function layoutMask() {
// here 400 is the same as the max-width style property
if (window.innerWidth >= 400) {
mask.style.left = '50%';
// to ensure centering, this sould be (max-width / 2)
mask.style.marginLeft = '-200px';
}
else {
mask.style.left = '';
mask.style.marginLeft = '';
}
// the same as width
if (window.innerHeight >= 400) {
mask.style.top = '50%';
mask.style.marginTop = '-200px';
}
else {
mask.style.top = '';
mask.style.marginTop = '';
}
}
最后,将这个函数分配给resize
事件,并立即执行以确保 <div>
在第一次加载时正确放置:
if (window.addEventListener) {
window.addEventListener('resize', layoutMask);
}
else {
window.attachEvent('onresize', layoutMask);
}
layoutMask();
我在我的 chrome 上试过了,但我确定它在 IE6 下不起作用,因为 IE6 不支持 position: fixed;
样式,但它应该适用于大多数浏览器。
我做了一个 jsfiddle用于测试。
我是一名优秀的程序员,十分优秀!