我只想有一个 100% 的窗口高度的侧边栏,但除了这个之外什么都不起作用:
#sidebarBack {
background: rgba(20, 20, 20, .3);
position: fixed;
width: 250px;
height: 100%;
left: 0;
}
我不想有position: fixed
,因为我有水平滚动的内容,所以固定的部分将保持,嗯,固定。
有没有办法做这样的事情,也许是relative
或absolute
职位?
这是一个快速的小提琴,仅用于测试和解释:JSFiddle<</p>
您可以使用新的和非常有用的 - 我无法想象什么 W3C-so-long vh
CSS 单元:
height:100vh;
tl;dr - 将html, body {height:100%;}
添加到您的 CSS 中。
CSS 中的百分比值继承自某个已经声明高度的祖先。在您的情况下,您需要告诉侧边栏的所有父母都是 100% 的高度。我假设#sidebarBack
是body
的直系孩子。
从本质上讲,上面的代码告诉#sidebarBack
是其父级的 100% 高度。它的父级(我们假设)是 body
,所以你也需要在body
上设置height: 100%;
。然而,我们不能止步于此; body
从 html
继承高度,所以我们还需要在 html
上设置height: 100%;
。我们可以停在这里,因为html
继承了它的属性 viewport
,它已经声明了 100%
的高度 .
这也意味着如果您最终将#sidebar
放入另一个div
,那么该div
也需要 height:100%;
.
下面是一个更新的 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;
}
首先,告诉 body 元素填充窗口,而不是缩小到内容的大小:
body { position: absolute; min-height: 100%; }
通过使用min-height
而不是height
,当内容比窗口长时,正文将被允许扩展到窗口的高度之外(即,这允许在需要时垂直滚动)。
现在,将"#sidebar"设置为position:absolute
,并使用top:0; bottom:0;
强制它填充父元素的垂直空间:
#sidebar {
position: absolute;
top:0; bottom:0;
left: 0;
width: 100px;
background: rgba(20, 20, 20, .3);
}
这里有几个jsFiddles:
- 内容短于窗口
- 内容长于窗口
如您所见,在这两个示例中,我保留了"#settings"部分的宽度设置,从而显示水平滚动按照您的要求工作。
尝试以下操作
#sidebarBack {
background: rgba(20, 20, 20, .3);
position: fixed;
width: 250px;
top:0;
bottom:0;
left: 0;
}
<</div>
div class="one_answers">试试这个 -
html,body{height:100%;}
#sidebar {
background: rgba(20, 20, 20, .3);
/*position: fixed;*/
width: 100px;
height: 100%;
left: 0;
float:left;
}
section#settings {
width: 62%;
height: auto;
display: inline-block;
position: relative;
margin-left: 100px;
float:left;
}