简体   繁体   中英

How to Limit Fixed-Position Element to Height of Browser Window?

I have a page with a fixed-position sidebar. I'd like the sidebar to be scrollable in the case where its content is too tall to fit within the browser window.

However, when I style the sidebar with overflow-y: scroll , the scrollbar shows up but it is disabled because the sidebar is tall enough to hold all the content even though it's too tall for the browser window.

Is there any way to restrict the height of a fixed-position element such that it will scroll when it's content extended below the bottom of the browser window?

A jQuery solution is acceptable for my application. Note that the sidebar does not extend all the way to the top of the window.

http://jsfiddle.net/nA8z4/

http://jsbin.com/iqibew/2 : This version shows a header, which the sidebar must appear below.

You need to set the height of the sidebar. Right now, your sidebar is as high as your text block and runs below the viewport (but you can't see that). If you set its height to 100% (or something else) the sidebar will display a scrollbar if all its content can't be shown at once.

So you need to change this:

div#fixed-div {
    position: fixed;
    left: 0;
    top 80px;
    width: 260px;
    background-color: silver;
    overflow-y: scroll;
}

To this:

div#fixed-div {
    position: fixed;
    left: 0;
    top 80px;
    width: 260px;
    background-color: silver;
    overflow-y: scroll;
    height: 100%;
}

Edit :

If you want a solution with maximum browser support (even older browsers), you'll need JavaScript. Here is a solution that depends on jQuery:

CSS:

* {
  margin: 0;
  padding: 0;
}

html, body {
    height: 100%;
}

div#header-div {
    height: 90px;
    background-color: lime;
}
div#fixed-div {
    position: fixed;
    width: 260px;
    background-color: silver;
    overflow-y: scroll;
}

JavaScript:

var bodyHeight = $('body').height();
var headerHeight = $('#header-div').height();
var sidebarHeight = bodyHeight - headerHeight;

$('#fixed-div').height(sidebarHeight);

Working JSFiddle: http://jsfiddle.net/nH7xR/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM