html - 即使用户滚动,如何将侧边栏锁定到窗口的高度?

标签 html css position alignment

我的页面上的某个元素遇到了一个小问题。我有一个侧边栏,我试图通过使用以下 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;
}

JSFiddle

另一种方法是给父容器 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;
}

JSFiddle

检查 learnlayout阅读有关定位的更多信息。

关于html - 即使用户滚动,如何将侧边栏锁定到窗口的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19486944/

相关文章:

html - Nightwatch - 使用按钮文本名称单击按钮

html - CSS:更改段落的字体大小会更改 H1 的显示大小

ios - 如何从UISlider 的自定义位置播放音频?

php - 网站本地化技术

html - 选项卡菜单中的 Bootstrap float div

html - 为链接尝试不同的伪类?

javascript - 表单表对齐问题

html - 有什么方法可以向嵌入式 SVG 添加类?

css - 如何在不同的桌面设备上应用相同的背景图像

CSS:为什么删除边框会严重影响 div 容器的位置?