Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if HTML height is set by style or by content

I have 2 divs:

<div id="div1"></div>
<div id="div2">div2</div>​

in my css:

#div1{ height:20px}​

Both divs have 20px height, check demo
How can I find out if the div have it's height due to content or have been set in css or inline style?
This helps me find out the dimensions have been set by the developer or just calculated by the browser.

like image 985
ilyes kooli Avatar asked May 11 '12 13:05

ilyes kooli


People also ask

Is height Auto by default CSS?

The default is height: auto in browser, but height: X% Defines the height in percentage of the containing block.

How do you find the content height?

Using jQueryjQuery has the . height() method, which returns an element's content height. For example, the following code returns 100, which is equal to the original height of div.

How is height determined CSS?

If 'height' is 'auto', the height depends on whether the element has any block-level children and whether it has padding or borders: If it only has inline-level children, the height is the distance between the top of the topmost line box and the bottom of the bottommost line box.


2 Answers

I found a way to achieve it :)

function getRealHeight(element){
    var height=0;
    if (element.children().length>0){
        var temp = $('<div></div>');
        temp.append(element.children());
        height = element.height();
        element.append(temp.children());
    } else {
        var html=element.html();
        element.html('');
        height = element.height();
        element.html(html);
    }
    return height;
}

​DEMO

like image 196
ilyes kooli Avatar answered Sep 20 '22 11:09

ilyes kooli


Use this function:

function emptyHeight ( elem ) {
    var $temp = $( '<div />' );
    var $elem = $( elem );
    var height;

    $temp.append( $elem.contents() );
    height = $elem.height();
    $elem.append( $temp.contents() );

    return height;   
}

The idea is to temporarily detach all child nodes from the element. An element with no children has a height of 0, unless its height is set via CSS.

Pass your DIV element into that function. If it returns 0, that means that the DIV does not have its height set via CSS.

if ( emptyHeight( yourDiv ) === 0 ) {
    // the DIV does not have any height value set via CSS
} else {
    // the DIV has a CSS height set
}
like image 41
Šime Vidas Avatar answered Sep 18 '22 11:09

Šime Vidas