html - 如何实现固定侧边栏?

标签 html css css-position

<分区>

我有这样的情况:

<!DOCTYPE HTML>
<html>
    <head>
        <title>test</title>
    </head>
    <style>
        #wrapper { width: 1100px; margin: 0px auto; }
        #wrapper #stream { width: 790px; float: left; border: 1px solid red;  }
        #wrapper aside { width: 270px; float: left;  border: 1px solid red; }
    </style>
    <body>
        <section id="wrapper">
            <section id="stream">
                some text...
            </section>
            <aside>
                <ul>    
                    <li>something</li>
                    <li>something</li>
                    <li>something</li>
                    <li>something</li>
                </ul>
            </aside>
        </section>
    </body>
</html>

即使页面向下滚动,我也不希望侧边栏移动。

我尝试将 aside 的位置设置为 fixed 但无法正确设置与左侧的距离。

我找到了一个使用 jQuery 的解决方案:

$(document).ready(function () {
    $(window).scroll(function () {
        $("aside").css('top', $(window).scrollTop()+'px');
    });
})

但是对于 Chrome 和 Safari,旁边的滚动条是分段的。

有什么帮助吗?

========================

解决方案:

<!DOCTYPE HTML>
<html>
    <head>
        <title>test</title>
    </head>
    <style>
    #wrapper {

        width: 1100px;
        margin: 0px auto;
    }
    #stream {
      width: 800px;
      background: #ccc;
      float: left;
    }
    #sidebar {
    float: left;
      border: 1px solid red;
      width: 200px;
    }
    aside {
      position: fixed;
      top: 20px;
      border: 1px solid red;
    }
    </style>
    <body>
    <section id="wrapper">
        <section id="stream">
                some text...
        </section>
        <section id="sidebar">
          <aside>
                <ul>    
                    <li>something</li>
                    <li>something</li>
                    <li>something</li>
                    <li>something</li>
                </ul>
          </aside>
        </section>
    </body>
</html>

最佳答案

为了使用toprightbottomleft 属性,您必须设置对象的 display 属性设置为 absoluterelativefixed

无论哪种方式,通过设置 position: fixed; 它不会在您滚动时移动。

关于html - 如何实现固定侧边栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15565754/

相关文章:

javascript - BackboneJS 删除背面的旧 View ?

html - 如何用div制作这样的模板(非表一)

c# - 为什么我的 GridView CommandField 中有一个有趣的 "block"?

html - 如何恢复绝对定位的叠加元素顺序?

html - 如何将元素定位在视口(viewport)左边缘之外?

controls - Google map v3 默认控制位置偏移

php - Flash对象使MySQL增加2

Javascript 正在删除要删除的行上方的行

css - 如何在 ngstyle 中正确使用 css "calc()'

css - float :right sidebar enjoys sitting below my content