【问题标题】:How do I lock a sidebar to the height of a window even when a user scrolls?即使用户滚动,如何将侧边栏锁定到窗口的高度?
【发布时间】:2013-10-29 11:57:02
【问题描述】:

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

【问题讨论】:

    标签: html css position alignment


    【解决方案1】:

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

    #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 了解更多关于定位的信息。

    【讨论】:

      【解决方案2】:

      使用 css position:fixed 固定侧边栏。

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

      $(function(){
          // assign to resize 
          $(window).resize(set_height);
      });
      
      function set_height() {
          $('#sidebar_id').height($(window).height());
      }
      

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        首先,我不明白在没有定义高度的情况下它是如何跨越 100% 的高度的。

        第二次使用position: fixed,而不是absolute。

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-05-26
          • 2015-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-23
          相关资源
          最近更新 更多