响应div高度相对于固定的HTML身体高度
由于大多数浏览器窗口是不同的大小取决于屏幕,我试图让网页没有滚动,而适合页面的全部内容到一个浏览器页面。我的身体有以下样式:响应div高度相对于固定的HTML身体高度
<body style="overflow:hidden;height:100%">
我想有彼此堆叠的前两名<div>
的。一个占据60%的高度,另一个占用40%,同时保持固定以覆盖整个浏览器视图端口。这可能吗?
我目前硬编码高度为我的<div>
,我刚刚意识到这可能适合我的浏览器,但其他人将无法看到相同的东西。
会根据浏览器的高度动态地为我的两个<div>
设置JS类的CSS类。那么这是一个很好的解决方案吗?
我知道这可能会带来另一个问题,我的div的内容被挤压或以一种奇怪的方式扩展,但我想我可以稍后处理。
如果你是supporting quite modern browsers(≥ IE9,火狐,Chrome,Safari浏览器,歌剧),你可以随时使用视计量单位: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>
的只有顺利的是,vh
计算在iOS7中是有问题的,因此您可能需要使用特定的@media
查询来为iOS7 Safari用户手动设置高度。
如果您想根据视口的高度动态设置div的高度,那么通常JavaScript是您的最佳选择。
在显示任何内容之前,计算窗口的高度,设置所需的高度,然后使内容可见。
在旁边的说明,个人来说,我不喜欢这种风格的网站。我认为它仅适用于应用程序样式的网站,它需要进行大量的可用性测试,因为它会打破标准的浏览器行为,并且需要大量的跨浏览器测试,因为最终会使用大量自定义代码。 </rant>
如果你不想任人VH和大众的东西,这将仍然足够了:
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;
}
祝你好运!