gpt4 book ai didi

vertical-alignment - 如何用 div 填充屏幕,然后在屏幕变得太大(达到最大高度)后将其居中?

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:05 25 4
gpt4 key购买 nike

目标:

  • 当窗口的宽高都很小时,div要和窗口一样大;

  • 当窗口宽度过大(>max-width)时,div应保持其宽度为max-width,并水平居中。

  • 当窗口高度过大(>max-height)时,div应保持其高度为max-height,并垂直居中

除了最后一点,下面的例子已经实现了一切。

如何让这个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>元素布局,所以我称之为ma​​sk:

<div id="mask"></div>

然后,将其样式化以填充整个文档,并给出 max-widthmax-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用于测试。

关于vertical-alignment - 如何用 div 填充屏幕,然后在屏幕变得太大(达到最大高度)后将其居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14579410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com