Reputation: 2058
Here's what I am looking to achieve. I have HTML along those lines (in reality I use a separate CSS file of course):
<div id="container" style="position:absolute; left:20px; top:20px; height:300px; width:400px;"> <div id="header" style="width:100%;">header stuff here...</div> <div id="content">content stuff here...</div> </div>
I want header to be auto sized with respect to height and the rest of the parent div to be occupied by content. The content should fill exactly - no scrollbars or anything. Assume modern browsers, I don't care about IE6 or even IE7.
All the examples I've seen so far assume fixed header height. Can auto-sized header be achieved without JavaScript, or is it beyond capabilities of modern browsers?
Upvotes: 2
Views: 7274
Reputation: 2058
It can be done with CSS after all. You need to use display:table
and have the content pane height at 100%. Unfortunately, you will also need an extra <div> inside header and content. JSFiddle link is here: http://jsfiddle.net/RBHXm/3/. You may also add footer if you'd like: http://jsfiddle.net/DE8pA/3/
You will also need to introduce padding to prevent margin collapse. Otherwise things like <h1> will look funny.
HTML:
<div id="container">
<div id="header" ><div><h1>Header stuff<br />here...</h1></div></div>
<div id="content"><div><p>content stuff here...</p></div></div>
</div>
CSS:
/* colors to make the demo clear: */
#container { background: #ddd; }
#header { background: #ddf; }
#content { background: #dfd; }
/* CSS provided in question: */
#container {
position: absolute;
left: 20px;
top: 20px;
height: 300px;
width: 400px;
}
#header {
width: 100%;
}
/* your fix: */
#container {
display: table;
}
#container > * {
display: table-row;
}
#content {
height: 100%;
}
#container > * > * {
display: table-cell;
padding: 0.01px;
}
/* optional styles to make it look pretty */
#content > div {
border: 2px solid green;
}
#header h1 {
text-align: center;
margin: 3px;
color: blue;
}
Upvotes: 1
Reputation: 10189
Take a look at this fiddle or its output. Try resizing the window.
HTML:
<div id="container" style="height: 100%;">
<div id="header" style="width:100% ">some stuff here...</div>
<div id="content">ome other stuff here...</div>
</div>
JS:
$(document).ready(function () {
var header_height = $("#header").height();
var content_height = $("body").height() - header_height;
$("#content").height(content_height);
});
$(window).resize(function () {
var header_height = $("#header").height();
var content_height = $("body").height() - header_height;
$("#content").height(content_height);
});
CSS:
html, body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#header {
height: auto;
background-color: green;
}
#content {
width: 100%;
background-color: blue;
}
The JS helps the content div to take all the available space even when we resize the window :)
Upvotes: 1