Determining Height of Elements Without CSS Height Rules
In the absence of a CSS height rule for an element, it can be challenging to obtain its height. The jQuery .height() method, which requires a pre-defined CSS height value, seems inadequate in this scenario. However, there are alternative methods to determine the height of an element.
jQuery .height()
Contrary to popular belief, jQuery .height() does not rely on a CSS height definition. It calculates the computed height of the element, making it suitable for scenarios where no explicit CSS height is specified.
DEMO
.height(): Retrieves the element's height without padding, border, or margin.
.innerHeight(): Retrieves the element's height including padding but excluding border and margin.
.outerHeight(): Retrieves the element's height including border but excluding margin.
.outerHeight(true): Retrieves the element's height including both border and margin.
Code Snippet for Live Demo
<code class="js">$(function() { var $heightTest = $('#heightTest'); $heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"') .append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>') .append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>') .append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>') .append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>') });</code>
The above is the detailed content of How to Determine Element Height in jQuery Without Explicit CSS Height Rules?. For more information, please follow other related articles on the PHP Chinese website!