April 11, 2012

create a scroll bar in a sidebar

Question by dan

I’m trying to create a scroll bar inside the #main div so that I can scroll that without scrolling the page or the title but it isn’t working. What am I missing?

My code is as follows:

CSS

#topbar {
    height: 40px;
    background-color: blue;
}

#sidebar {
    position: absolute;
    top: 40px;
    bottom: 0px;
    width: 80px;
    overflow: hidden;   
}

#title {
    height:30px;
    background-color: red;
}

#main {
    height: auto;
    overflow: scroll;
}

HTML

<div id="topbar">
    hello
</div>
<div id="sidebar">
    <div id="title">
        title
    </div>
    <div id="main">
        <!-- lots and lots of text-->
    </div>
</div>

You can find an example JSFiddle here: http://jsfiddle.net/PTRCr/

Thanks

Answer by Starx

CSS are stylesheet whose only purpose are to style document. They cannot investigate a pre-existing elements.

The only ways are whether the size of the div has to be fixed or you have to use some JavaScript to find out the exact height. The ways of which this can be done with CSS have already been presented by other users.

So, here is a way you can do using jQuery

$("#main").height($(document).innerHeight()-$("#title").outerHeight() - $("#topBar").outerHeight());

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!