如何使div 100%的窗口高度? [英] How can I make a div 100% of window height?
问题描述
我只是想有一个侧边栏将是100%的窗口高度,但没有什么工作除了这一点:
I just want to have a sidebar that will be 100% of window height, but nothing works except this:
#sidebarBack {
background: rgba(20, 20, 20, .3);
position: fixed;
width: 250px;
height: 100%;
left: 0;
}
我不想有 position:fixed
,因为我有水平滚动的内容,所以固定的部分将保持,很好,固定。
I don't want to have position: fixed
, because I have horizontally scrollable content, so a fixed part would remain, well, fixed.
有什么办法做这样的事,可能是相对
或绝对
位置?
Is there any way to do such a thing, maybe with relative
or absolute
position?
一个快速小提琴只是为了测试和解释:
JSFiddle
Here's an quick Fiddle just for a test and explanation: JSFiddle
推荐答案
tl; dr - 添加 html,body {height:100%;}
CSS中的百分比值继承自已声明高度的某个祖先。在你的情况下,你需要告诉你的边栏的所有父母是100%的高度。我假设 #sidebarBack
是 body
的直接子级。
Percentage values in CSS are inherited from some ancestor that already has height declared. In your case, you need to tell all parents of your sidebar to be 100% height. I'm assuming that #sidebarBack
is a direct child of body
.
基本上,上面的代码告诉 #sidebarBack
是其父级的100%高度。它的父级(我们假设)是 body
,因此您需要设置 height:100%;
on body
。我们不能停在那里; body
从 html
继承高度,因此我们在 html
上设置 height:100%;
。我们可以在这里停止,因为 html
从视口
继承它的属性,它已经有一个声明的高度 100%
。
Essentially, your code above is telling #sidebarBack
to be 100% height of its parent. Its parent (we are assuming) is body
, so you need to set height: 100%;
on body
as well. We can't stop there, however; body
inherits height from html
, so we also need to set height: 100%;
on html
. We can stop here, because html
inherits its properties from viewport
, which already has a declared height of 100%
.
这也意味着如果你最终将 #sidebar
放在另一个 code>,那么
div
也需要 height:100%;
。
This also means if you end up putting the #sidebar
inside another div
, then that div
also needs height:100%;
.
以下是 更新的JSFiddle 。
Here is an Updated JSFiddle.
已将CSS更改为:
html, body {
height:100%;
}
#sidebar {
background: rgba(20, 20, 20, .3);
width: 100px;
height: 100%;
left: 0;
float:left;
}
section#settings {
width:80%;
float:left;
margin-left:100px;
position:fixed;
}
这篇关于如何使div 100%的窗口高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!