valepu
valepu

Reputation: 3315

CSS/Javascript: Keep a div size based on container size

I have a div which contains 2 divs, one has fixed height. I want to make sure that the 2nd div's height is exactly as much as the height of the container div minus the other div's height. This height can't be manually set because it's often resized.

<div id="container" style="height: 50%"> 
<div id="header" style="height: 30px;"> 
</div> 
<div id="content"> 
</div> 
</div>

i have tried with jquery on resize but i think i wrote something wrong:

$(document).on("resize", "#container", function (event) {
    $('#content').height($('#container').height()-$('#header').height());
});

Is there any way (Javascript, CSS) to achieve this?

Upvotes: 0

Views: 2457

Answers (3)

avrahamcool
avrahamcool

Reputation: 14094

I have a pure CSS solution for you, Check out that Working Fiddle

HTML:

<div id="container">
    <div id="header"></div>
    <div id="content"></div>
</div>

CSS:

#container {
    height: 300px; /*Whatever fixed height you want*/
}
#container:before {
    content:'';
    float: left;
    height: 100%;
}
#header {
    height: 30px;/*Whatever fixed height you want, or not fixed at all*/
    background-color: red;
}
#content {
    background-color: blue;
    /*No height spesified*/
}
#content:after {
    content:'';
    clear: both;
    display: block;
}

Upvotes: 1

stephenhay
stephenhay

Reputation: 2874

An alternative to the jQuery method is CSS Flexbox:

#container {
  display: flex;
  flex-direction: column;
}

#content {
  flex: 1;
}

See the demo. Unfortunately, this will only work in browsers supporting the latest Flexbox syntax. (http://caniuse.com/#search=flexbox) Backward compatible code is possible using old syntaxes as well, but will be sightly more involved. See David Storey's article at http://coding.smashingmagazine.com/2013/05/22/centering-elements-with-flexbox/ for more on how to do that.

Upvotes: 2

ced-b
ced-b

Reputation: 4065

Your main problem seems to be that you have to size the element initially and then keep listening to the resize event:

function handleResize() {  
   $('#content').height($('#container').innerHeight()-$('#header').height()); 
}

$(window).on("resize", handleResize);

handleResize();

Also, the resize event should be attached directly to the window.

Otherwise, I recommend the use of innerHeight() for the container as that takes into account padding.

Also I made some fixes to your CSS for this to fully work:

#container {
   position: absolute;
   width: 100%;
   height: 50%;
}

See full fiddle here: http://jsfiddle.net/kjcY9/1/

Upvotes: 1

Related Questions