使元素固定位置,但如果内容太大则按页面滚动

Mat*_*ann 6 html css position

请参阅此网页.

  1. 首先尝试滚动它,看左边的栏保持固定.
  2. 调整窗口的高度,以便不会显示左侧栏的所有内容.现在滚动.这次,左栏不固定.

在此页面中,有一个jquery计算左栏的高度,将其与窗口高度进行比较,然后使左栏位置固定或绝对.

但是,我想知道是否可以通过HTML和CSS实现类似的东西,而不是使用jQuery或类似的东西.

有什么建议?简而言之,我正在寻找的是一个内容保持固定的栏,但如果内容溢出则滚动.但滚动应该与整个页面一起.

Rae*_*kye 8

您可以使用媒体查询来指定特定屏幕尺寸的CSS(以及其他类似的东西),这样如果屏幕太小,您可以使用一个样式表.我不是专家,所以没有例子,但请看一下http://css-tricks.com/css-media-queries/.抱歉! 但你猜你想通了:)

编辑:工作结果如下:

#leftnav {
    /* default look */
    width: 300px;
    position: fixed;
    top:0;
    height: 100%;
}

/* set the size at which the content is clipped and we cannot have fixed position */
@media all and (max-height: 500px) {
    /* things inside here will only have an effect if the browser window shows
       less than 500 px in the height, so here I apply the special rules */
    #leftnav {
        position: absolute;
        height: auto;
        /* etc.. */
    }
}
Run Code Online (Sandbox Code Playgroud)