由于大多数浏览器窗口的大小因屏幕而异,我试图允许网页不滚动,同时将页面的全部内容放入一个浏览器页面。我的身体有以下风格:
<body style="overflow:hidden;height:100%">
我想把两个<div>
叠在一起。一个占据60%的高度,另一个占据40%,同时保持固定以覆盖整个浏览器视图端口。这可能吗?
我目前正在为我的<div>
硬编码高度,我刚刚意识到这可能适合我的浏览器,但其他人将无法看到同样的东西。
根据浏览器的高度在JS中为我的两个<div>
动态设置css类是一个很好的解决方案吗?
我知道这可能会带来另一个问题,我的div内容被以一种奇怪的方式挤压或扩展,但我想我以后可以处理这个问题。
如果您支持非常现代的浏览器(≥IE9、Firefox、Chrome、Safari、Opera),您可以始终使用视口测量单位:vh
和vw
:)
body {
margin: 0;
padding: 0;
}
.wrapper {
width: 100%;
/* or 100vw, that's the same */
height: 100vh;
}
.h60 {
background-color: #eee;
height: 60vh;
}
.h40 {
background-color: #333;
height: 40vh;
}
/* Unrelated styles, for display purposes only */
.wrapper > div {
display: flex;
font-family: Helvetica, Arial, sans-serif;
align-items: center;
justify-content: center;
}
p {
margin: 0;
}
.wrapper > div:last-child {
color: #eee;
}
<section class="wrapper">
<div class="h60">
<p>I have a height that is 60% of the viewport.</p>
</div>
<div class="h40">
<p>I have a height that is 40% of the viewport.</p>
</div>
</section>
唯一的问题是,iOS7中的vh
计算存在缺陷,因此您可能需要使用特定的@media
查询来手动为iOS7 Safari用户设置高度。
如果您想根据视口的高度动态设置div的高度,那么JavaScript通常是您的最佳选择。
在显示任何内容之前,请计算窗口的高度,设置所需的高度,然后使内容可见。
顺便说一句,就我个人而言,我不喜欢这种风格的网站。我认为它只在应用程序风格的网站中有用,它需要大量的可用性测试,因为它打破了标准的浏览器行为,还需要大量的跨浏览器测试,因为你最终会使用大量的自定义代码。</rant>
如果你不想要花哨的vh和vw东西,这仍然足够:
html, body{
height: 100%;
}
body{
overflow: hidden;
}
.foo{
height: 60%;
background: #369;
}
.bar{
height: 40%;
background: #693;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="foo"></div>
<div class="bar"></div>
</body>
</html>
还有另一种可能性:
http://codepen.io/panchroma/pen/ZYwXLP
在你的情况下,我认为像我在这里所做的那样使用vh,或者flexbox有很多值得推荐的地方,你最终会得到漂亮干净的代码。
HTML
<div class="top">top div</div>
<div class="bottom">bottom div</div>
CSS
.top{
height:60vh;
}
.bottom{
height:40vh;
}
祝你好运!