100% Height Div with 2 lines of code

2016 Edit: This post is really out-dated. If you are looking for a solution for 100% height divs, please use modern css as described here /2016/modern-100-percent-height-css/

EDIT: This post has several code-blocks of JavaScript to keep two divs at an equal height. I recommend the last method, if you are using jQuery — It seems to be more adaptive to different div content, working in more situations.

Check out the DEMO first, to see if this is what you want

The problem: Creating a div that auto-expands to 100% height of its container. The most common occurrence would be creating a two column layout for a menu, sidebar ads, etc…

The solution that never actually works:

“Since divs automatically inherit the height of their parent, if your parent doesn’t have height set, you cant get 100% of nothing. Set the parents height and it will work.”  Pshaw, I say.  While this may be the accepted standards mantra, I have never seen it actually work in a modern browser.

100 Percent Div Tutorial
Div! Y U NO Expand?!?

The Easy Solution (in 2 lines of code):

Working Demo on jsfiddle

Well, that’s actually 4 lines, if you include the script tag… But just 2 lines of JavaScript.

If you would like to keep the expanding div from collapsing too far, or expanding to much, simply add a conditional statement around the second line, like so:

Short Explanation:

Line 1 creates a new variable “h” and assigns this variable the height of an element found. This does not return the “height:” as specified in CSS, it returns the actual height of the document as it is displayed on the screen.

Line 2 fills the “height:” style value of the other, shorter, element with the variable h + “px”

Put this code near the end of your document, probably right before the body tag, and it will run right when the page loads. You could also wrap this in a jquery $(window).load, or even a $(document).ready. As it is, though, there is no library dependency – just plain-old-JavaScript!

Or, do it with jQuery instead:

Commenter Ivan couldn’t get this code working for him, so he rewrote it using jQuery. I have further rewritten his original code to be a bit shorter, and activate when the content of both divs has fully loaded. I recommend this method — if you are already loading jQuery — as it seems to work much better with dynamically loaded content.

Working jQuery demo


Edit #2 — There is a jQuery plugin called equalHeight that accomplishes this pretty easily

Check out my post 100% height using jQuery for more information about it.