Reputation: 1383
How to make div scrollable, without hard-coding its height? Usually when you want to make div scrollable, you need to set max-height, otherwise it will be expanding.
#element {
overflow:auto;
max-height: 100px;
}
In my case, I want height to be restricted by parents height (and parent is resizable), not by setting it in CSS.
Here is JSFiddle: http://jsfiddle.net/mbrnwsk/58qSc/1/
Upvotes: 2
Views: 2147
Reputation: 174
height:100%;
will set it equal to the parents height.
See it here
EDIT: The comment is right: Need to add padding to the parent
#parent {padding-bottom: 1em;}
Upvotes: 2
Reputation: 66093
In order for the #content
to stretch to fill the remaining space in the parent minus the height of the #title
element, you can do it with either CSS or JS. The CSS solution is simple, but you will have to adjust the offset of the top
to ensure that it fits properly. By setting the other three offsets (left, bottom and right) to zero, we thereby force the #content
element to stretch out completely.
#parent {
border: 3px solid;
height: 150px;
position: relative;
}
#content {
overflow-y: auto;
overflow-x: hidden;
background: cyan;
top: 16px; /* This is based on the assumption that #title has a height of 16px */
right: 0;
bottom: 0;
left: 0;
position: absolute;
}
http://jsfiddle.net/teddyrised/58qSc/3/
For a more responsive solution, you will need to rely on JS to fetch the height of #title
, and then set the top
property of #content
accordingly — the advantage of this is that it will respond well when the viewport size changes, also when the height of #title
changes.
For the CSS, it's the same as above but we remove the top
declaration. Instead, we delegate this to JS instead:
$(function() {
$("#parent").resizable();
// Function to set height
var setContentHeight = function() {
$('#content').css('top', $('#title').outerHeight());
}
// Recalculate when viewport changes
// You can also bind this function to events that manipulate the dimension of #title
$(window).resize(setContentHeight);
// Run once when DOM is ready
setContentHeight();
});
http://jsfiddle.net/teddyrised/58qSc/4/
The advantage of the JS-based solution is that:
top
by binding the setContentHeight()
function to any events that you can foresee will change the dimensions of #title
.top
value when you alter the paddings, margins, heights (min-, max- or height), line-height of #title
, or any of its children (if they exist)Upvotes: 2