Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a div auto-adjust its height between two divs, according to window height using CSS/Javascript?

I have a div positioned at the top of the body and another div positioned at the bottom of the body

Now I want to place a div between those two divs and have its height take the max space available between those two divs.

The vertical space between those two divs is not fixed, meaning that when the user decreases/increases the height of the window, I want the middle div to readjust its height accordingly.

More specifically :

<body>
  <div style="position: fixed; top: 0px; left: 0px; width: 200px; height: 100%;">
    <div style="float: left; height: 50px, width: 200px; background-color: green;"/>
    <div style="float: left; height: ???? ; width: 200px; background-color: red;"/> 
    <div style="float: left; height: 50px, width: 200px; background-color: blue;" />
  </div>
</body>

So basically imagine a green rectangular fixed at the top left of the page, a blue one fixed at the bottom left of the page and a red column between them readjusting its height according to the height of the window.

How can I achieve this?

Setting its height at 100% simply makes the middle div expand its height to the bottom of the window which is not what I want. I need it to stop where the blue div starts. Also, making its height e.g. 73% doesn't make it auto-adjust itself correctly when the window height is changed either.

like image 885
The Random Guy Avatar asked Mar 20 '26 00:03

The Random Guy


1 Answers

Assuming you are doing this because you want a footer that is flushed to the bottom of the page, then this will achieve a similar effect: http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page

However solution does not resize the middle div but merely positions the footer over it and then use padding to prevent the contents of the middle div from going onto the footer.

If you want to actually change the size of the middle div, here's the JavaScript for it using jQuery: http://jsfiddle.net/BnJxE/

JavaScript

var minHeight = 30; // Define a minimum height for the middle div

var resizeMiddle = function() {
    var h = $('body').height() - $('#header').height() - $('#footer').height();
    h = h > minHeight ? h : minHeight;
    $('#body').height(h);
}

$(document).ready(resizeMiddle);
$(window).resize(resizeMiddle);

HTML

<div id="container">
   <div id="header"></div>
   <div id="body"></div>
   <div id="footer"></div>
</div>

CSS

html,
body {
   margin:0;
   padding:0;
   height: 100%;
}

#header {
   background:#ff0;
   height: 100px;
}
#body {
   background: #aaa;
}
#footer {
   height: 60px;
   background:#6cf;
}
like image 114
darkmirage Avatar answered Mar 22 '26 14:03

darkmirage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!