How to get a scrollbar in a div with fixed header

2019-01-24 06:36发布

问题:

I have an website and some problems with the scrollbar.

What I want I can best explain with this image.

But I can't get the scrollbar like this.

I have tried some, here is the jsfiddle

In this fiddle I also have:

div[role="main"]
{
    overflow-y: scroll;
    margin: 60px 0;
}

But this margin is not OK, how do I know what margin I need without knowing the header and footer height.

回答1:

This can be slowed by using padding and box-sizing = border-box on body ( with body height 100% it will count padding into height, so the box with scroll will be exactly between header and footer)

html {
 overflow: hidden;
 height: 100%;
}

body {
 padding: 60px 0px;
 height: 100%;
 box-sizing: border-box;
}

div[role="main"] {
 overflow-y: scroll;
 height: 100%;
}

see http://jsfiddle.net/wPucQ/

EDIT: Added forgotten HTML tag in code



回答2:

You need to give the scrollable element a height so the scroll-bar position can be calculated.

div[role="main"]
{
    height:400px;
    overflow-y: scroll;
    margin: 60px 0;
}

http://jsfiddle.net/gkxV4/



回答3:

Try to mention Min-height or height for this div div[role="main"]{ overflow-y: scroll; margin: 60px 0; min-height:400px;}



回答4:

See my fiddle for entire logic fiddle http://jsfiddle.net/MA9k3/7

Jquery code:

var doc_height = $(window).innerHeight();

var header_height = $("header").height();
var footer_height = $("footer").height();

var div_height = doc_height - (header_height + footer_height);

$("#content").css({
    "height": (div_height - footer_height) + "px",
    "margin-bottom": footer_height + "px"
});

alert($("#content").height());