Jeroen
Jeroen

Reputation: 837

How do I determine the actual height of a HTML DOM element independent of the height specified in CSS?

See this jsFiddle: http://jsfiddle.net/kb2vN/1/

The height of the div 'mytext' as specified in CSS is 100. The total offsetHeight of the 3 paragraphs in the div is 3 * 40 = 120. Its this value (120) that I am after. Why is this value not returned by document.getElementById('mytext').offsetHeight? It would be logical that the offsetHeight of a parent element is the sum of the offsetHeights of its child nodes.

If I do NOT set the height of the 'mytext' div in CSS to 100px, the (in my opinion) correct offsetHeight of 120 is returned. But not setting the height in CSS is not an option in my case.

Why does the offsetHeight of the div correspond to the CSS height, and is there an alternative height property that reflects the actual div height, even if a height is specified in CSS?

By the way, I use Chrome as my web browser.

EDIT I realize that I haven't been totally clear on the purpose of all this. In the end I want to check whether the actual contents of a div (that are put in the div dynamically) do not cause the div to take up more than a specified maximum height (by comparing the div's offsetHeight to the max. height allowed). Since I want to check in JavaScript whether this is the case, using properties like min-height or max-height does not seem to make sense.

Upvotes: 2

Views: 3318

Answers (4)

Andreas Wong
Andreas Wong

Reputation: 60516

You are looking for getScrollSize().y

http://mootools.net/docs/core/Element/Element.Dimensions

Returns an Object representing the size of the target Element, including scrollable area. The following method is also available on the Window object.

http://jsfiddle.net/kb2vN/7/

You can do comparison as follows:

if($('mytext').getScrollSize().y != $('mytext').offsetHeight) {

http://jsfiddle.net/kb2vN/11/

Upvotes: 0

js1568
js1568

Reputation: 7032

If you temporarily set the height of the element to auto, then you can test for the offsetHeight with the element expanded to fit its contents. Then set the height of the element back to the previous value.

Upvotes: 0

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

clientWidth and clientHeight properties return actual size of an element.

Upvotes: 0

James Montagne
James Montagne

Reputation: 78630

If you add a border and some additional comment you will see why this is correct and IS the offset height:

http://jsfiddle.net/kb2vN/4/

You'll notice that the element #mytext does only take up 100 px. The content simply overflows it. If you put content after the element, you will see that it starts after only 100 px and the overflow from the box goes right on top of it.

I think what you really want is min-height:

http://jsfiddle.net/kb2vN/6/

Upvotes: 1

Related Questions