0

我的页面上的一个元素遇到了一个小问题。我有一个侧边栏,我试图通过使用以下 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% 的高度(减去顶部的 50 像素)。问题是它本质上将框分配给窗口的确切高度,因此当我向下滚动时,框会滚动而不是锁定在窗口底部。任何想法如何解决这个问题?

4

3 回答 3

1

position:fixed如果您想sidebar将 固定在某个位置,则必须使用:

#sidebar {
    width: 180px;
    padding: 10px;
    position: fixed;
    top: 50px;
    bottom: 0;
    background: #eee;
    color: #666;
}

JSFiddle

另一种方法是给父容器 position:relative,并在他的孩子身上 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以阅读有关定位的更多信息。

于 2013-10-21T05:43:26.547 回答
0

使用 cssposition:fixed使侧边栏固定。

为了根据屏幕高度锁定高度,我将使用 javascript/jquery:

$(function(){
    // assign to resize 
    $(window).resize(set_height);
});

function set_height() {
    $('#sidebar_id').height($(window).height());
}

希望有帮助

于 2013-10-21T05:41:01.723 回答
0

首先,当没有定义高度时,我不明白它是如何跨越 100% 的高度的。

其次使用position: fixed而不是绝对。

其次,我想推荐一种似乎更合适的定位方式。在主容器 div 的末尾,在它的结束标记之前,把这个

<div style="clear: both;"></div>

并使主容器也向左浮动,或者如果这不能给您想要的东西,则向右浮动。令人惊讶的是,这样一个常见的布局如何正确地做起来感觉很棘手。(至少对于像我们这样的新手来说)。我可能是错的,这可能不是更好的方法,但这是我会这样做的方式。您添加的额外 div 是为了让浮动 div 占用空间,除此之外,如果它不起作用,请将侧边栏的高度设置为 100%,或者如果您认为它会溢出,请告诉我我会添加到我的答案中.

于 2013-10-21T06:09:18.207 回答