http://blogs.clariusconsulting.net/eze

Ezequiel Sculli

Go Back to
eze′s Latest post

How to: Expand Div/Tables Height to 100% using JQuery

As a web developer, one of the problems that you might face is that divs and tables cannot expand themself to go full height just using CSS.
After researching about it for a while, I detected that the only way to fix it is using JavaScript. Of course you can take advantage of JQuery to make it a little bit easy.
Below you can find the solution that I designed for this problem:
function autoScaleHeight () {
    $(\".autoScaleHeight\").each(function () {
        var top = 0;

        $(this).siblings().each(function () {
            if ($(this).css(\"float\") == \"none\" &&
                $(this).css(\"display\") != \"none\" &&
                !$(this).hasClass(\"omitHeight\")) {

                top += $(this).height() +
                       calculateElementMarginAndPadding(this);
            }
        });

        $(this).height($(this).parent().height() -
                       top -
                       calculateElementMarginAndPadding(this));
        });
};

function calculateElementMarginAndPadding (element) {

    return parseFloat($(element).css(\"marginTop\")) +
           parseFloat($(element).css(\"marginBottom\")) +
           parseFloat($(element).css(\"paddingTop\")) +
           parseFloat($(element).css(\"paddingBottom\"));

}
The autoScaleHeight function iterates over all elements that has class “autoScaleHeight” and expand them to 100% their container’s height. Also, the function take into account siblings, in that cases, siblings height will be subtracted from the container’s height, so the “autoScaleHeight” element expand its height filling all available space in the container:
  • [Element].Height = [Container].Height – {[Sibling].Height}
Finally, all siblings that have class “omitHeght” are omitted from the previous formula.
Note: An interesting thing about elements’ height is that Margin and Padding are not included in the Height’s value. For that reason, calculateElementMarginAndPadding is used as a helper to work around this behavior.
Thanks,
Ezequiel
Comments