100% Height Div with 2 lines of code

Share on Facebook2Share on Reddit0Tweet about this on Twitter9Share on Google+1

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.

Share on Facebook2Share on Reddit0Tweet about this on Twitter9Share on Google+1
  • http://robertfauver.com Robert Fauver

    Sweet! I had an issue with body height:100% in my CSS last week and this is a great alternative.

    • dfdd

      gfdfdgdddd

      • assasa

        asdasasdasdasdadasdsa

  • admin

    Wonderful! I’m glad you got some use out of it. Hopefully the script saved you some sleep as well, as it took hours of frustration to decided to come up with my own solution. Let me know what site you use it on. I’d love to see it in action

  • James Curtis

    Hi there,
    I have an html slide show using java script and I was wondering if it was possible to put inside the main ‘red’ border of your example – so as i change the size of the window the slideshow and all its elements will change size

    is this possible?

    thanks
    James

  • James Curtis

    THIS IS THE CODE:

    Slideshow 2!

    .slideshow {
    float: left;
    margin: 0px;
    }

    window.addEvent(‘domready’, function(){
    var data = { ‘1.jpg': { caption: ‘1’ }, ‘2.jpg': { caption: ‘2’ }, ‘3.jpg': { caption: ‘3’ }, ‘4.jpg': { caption: ‘4’ }};

    new Slideshow(‘overlap’, data, { captions: { delay: 9999999999 }, delay: 3000, height: 300, hu: ‘images/’, width: 400 });
    });

    • admin

      James,

      This tutorial applies to setting the height of the divs on page load using a javascript function. To have your divs automatically re-size with each image should be a simple matter of applying the correct css property.

      However, having the slideshow elements and images automatically resize is another thing all-together. It may be addressed in your particular slide show function.

      Good Luck!

  • http://www.amusesmile.com Josh

    Hey this is awesome but any ideas why it’s not working in Chrome? It looks like it doesn’t check the size the same way or something so the content is always 0px. I was able to get around it by putting an if(h>300) statement in and then just defaulting to 300px but that’s pretty lame…

    • http://www.amusesmile.com Josh

      No actually it has to do with loading images within content. It’s like the div is 0px until the image contained within it is fully loaded. One it’s fully loaded it resizes but by then the menu div has already tried to resize to 0px. If you reload the page in firefox it automatically caches the image so then it will size correctly but chrome doesn’t do that. I’ll try to think of a solution but that just really sucks for now.

      • admin

        Josh, great catch. If you are using jQuery, you could trigger the script on $(document).ready(); However, that really seems like quite the hack.

        Honestly, I have been mulling-over whether or not to redo this post with some valid css, as it was written almost 1 year ago, and css compliance in browsers has come along way.

      • admin

        Ps. that data visualization on your site is pretty rocking. Thought I’d throw in a link for ya!

  • http://www.inextyn.com/ Ivan

    It actually didn’t work for me. I made it with jQuery and here is the code if anyone wants to use it:


    $(function(){
    var H = $("#container").height();
    $("#menu").height(H);
    });

    • admin

      Ivan, thanks for the code. I like your solution to the problem! Infact, if you check back, you’ll find I have re-written it a bit, and included it in the post. Thanks :)

  • http://www.albinal.com Albinal

    I’m using the JQuery method which works perfectly, except in Chrome, like Josh says. What a pain! :-/

  • http://www.albinal.com Albinal

    I specified the height of my images with CSS and then Chrome can work out the height of the div they’re in! :-)

  • Eric

    Many thanks. Looked for this solution all over the place and this actually works!

  • Sanaj M Shaji

    Thanks, it saved me from a real trouble.

  • Piyush

    Hi,

    I have face div height problem. i tried ur code. It solve some problem as well as create also.
    some time if right panel data is less compare to left then it decrease the height left panel.

    Actually my right Panel data is dynamic it picking the data from Widgets / MLS listing.

    Please let me know your valuable feedback / opinion on this.
    Regards.

  • Thallam

    beautiful !, thanks Mike

  • Vaishali Work3128

    Ya Its working fine  ..Thanx

  • WouterDS

    What’s happend to unobtrusive javascript?

  • Mads Thines

    Thank you, thank you, thank you!

  • Michel Simão

    PERFECT!

  • Joao Gabriel G Marques

    Man, you’re FAN-TAS-TIC! Thanks.

  • Jake

    Nice and it works!

  • Juliet

    Awesome .. it works…

  • HaydenCarrigg

    Hi this code is fantastic!

    But I would like eliments to adapt when the window size changes, currently if i shrink the window size, my coloured column on the left stays the same size, but the white column on the right has more text and grows larger than the left.

    Any possible fixes?

    (sorry i’m a java script noob!)

    • Jedediah White

      Same thing here, but presumably the end-user is already loading it on the screen size they’ll use for the rest of their visit, so I think I’ll leave it be for the moment.

  • http://jamiegoodwin.net/ Jamie Goodwin

    You LEGEND! Been trying the CSS only versions but they don’t play well with float. I’ve trimmed it down to a single line just to squeeze a few extra characters out of it:

    document.getElementById(‘child’).style.height = document.getElementById(‘parent’).offsetHeight + “px”;

  • Ankush

    nice help… really thank you

  • Anahit Aida Ghazaryan

    Thanks for this idea…It’s really helps me so))

  • Ellisafus

    Thank you! *-* It didn’t solve my problem completely but after a little change it worked perfectly :D thank you so much!