CSS: how to get scrollbars for div inside container of fixed height
Code from the above answer by Dutchie432
.FixedHeightContainer {
float:right;
height: 250px;
width:250px;
padding:3px;
background:#f00;
}
.Content {
height:224px;
overflow:auto;
background:#fff;
}
This is a great question because the answer is not immediately obvious, for such a simple task. The problem has hit me several times over the years, and It seems I always have to think about it before I get it right.
Below is my solution which uses (only) two CSS-classes, 'innerDiv' and 'outerDiv'.
<div id="outerDiv">
<div id="innerDiv">
A <p> B <p> C <p> D <p>
</div>
</div>
<style>
#outerDiv
{ height : 200px;
margin : 44px; border: solid 4px Red;
}
#innerDiv
{ height : 80%;
overflow-y : auto;
border : solid 4px Green; font-size: 300%;
}
</style>
Why does that work, and why do I say the answer is "not immediately obvious"?
In the example above both the outerDiv and innerDiv have fixed height because we set the height: -property for both of them.
We have the innerDiv height less than the height of the outerDiv. Therefore innerDiv "fits" into the outer-div and therefore the outer div should not get a scrollbar, right? Yes except if the innerDiv has so much content that it does not fit into the fixed height of the innerDiv but overflows. Therefore the question is how can we prevent the inner div from "overflowing"?
The way to prevent the innerDiv from overflowing is to give it the attribute "overflow: auto", or "overflow-y: auto" if we just want to prevent vertical overflow.
The reason the solution is "not immediately obvious" is this: The default value of 'overflow' is NOT 'auto', but 'visible'.
One might (erroneously) assume that the default value of overflow is "auto", because then everything should be auto-matically taken care of, right? Not so fast, the default of overflow is 'visible', NOT 'auto'.
So if you remove the "overflow-y:auto" from the example above there will be no scrollbars. If you remove it but add it to the outerDiv, the outer div will have the scrollbar, which is NOT what we want. If you have it in both then only innerDiv will have it.
setting the overflow
should take care of it, but you need to set the height of Content
also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.
See Example: http://jsfiddle.net/ftkbL/1/
FWIW, here is my approach = a simple one that works for me:
<div id="outerDivWrapper">
<div id="outerDiv">
<div id="scrollableContent">
blah blah blah
</div>
</div>
</div>
html, body {
height: 100%;
margin: 0em;
}
#outerDivWrapper, #outerDiv {
height: 100%;
margin: 0em;
}
#scrollableContent {
height: 100%;
margin: 0em;
overflow-y: auto;
}