我的页面上的某个元素遇到了一个小问题。我有一个侧边栏,我试图通过使用以下 CSS 来跨越页面的高度:
#sidebar {
width: 180px;
padding: 10px;
position: absolute;
top: 50px;
bottom: 0;
float: left;
background: #eee;
color: #666;
}
相应的 CSS 与您所期望的差不多:
<div id="header">
The header which takes up 50px in height
</div>
<div id="main-container">
<div id="sidebar">
The sidebar in question
</div>
<div id="main-content">
The rest of my page
</div>
</div>
大部分代码都按预期工作。当页面呈现时,它跨越 100% 的高度(从顶部减去 50px)。问题是它基本上将框分配给窗口的确切高度,因此当我向下滚动时,框会滚动离开,而不是保持锁定在窗口底部。有什么解决办法吗?
最佳答案
如果你想让sidebar
固定在某个位置,你必须使用position:fixed
:
#sidebar {
width: 180px;
padding: 10px;
position: fixed;
top: 50px;
bottom: 0;
background: #eee;
color: #666;
}
另一种方法是给父容器 position:relative
,在他的child position:absolute
- 但是父元素必须有一些 height
以便子元素采用它的高度。
html,body{
position:relative;
height:100%; /* some height */
}
#sidebar{
width: 180px;
padding: 10px;
position: absolute;
top: 50px;
bottom: 0;
background: #eee;
color: #666;
}
检查 learnlayout阅读有关定位的更多信息。
关于html - 即使用户滚动,如何将侧边栏锁定到窗口的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19486944/