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.
The default is height: auto in browser, but height: X% Defines the height in percentage of the containing block.
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.
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.
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With