Ravinder Singh
Ravinder Singh

Reputation: 3133

How to calculate height of div in jQuery?

I am in such a situation that I have to set height of a div depends on the amount of content in it, I can't give min-height in it. I know we can calculate height of div by :

$("#divid").height();

So is there any way we can calculate height of a div without having height parameter in it and give height to that div depends on the amount of content in it.

I hope I explained it clearly.

Thanks

Upvotes: 4

Views: 21984

Answers (4)

loganfsmyth
loganfsmyth

Reputation: 161647

Your wording is a bit confusing, but I think you are asking how to calculate the size of the content inside a div even if the div has a different height applied. For that you can use the element's scrollHeight.

$('#divid')[0].scrollHeight

If you just want to know how to calculate the height of an element even though it has no attribute/style for height, you can just use what you have written in the question. .height() computes the height of the element directly from the browser rendered values, not from the attributes specifically.

Upvotes: 6

Jai
Jai

Reputation: 74738

You have two ways doing it:

$("#parent").height($("#child").outerHeight(true));
//-----------------------------^^^^^^^^^^^--^^^^-----outerHeight(true) will give
//---------------------------------------------------you the total height 
//---------------------------------------------------including top bottom margins

more info .outerHeight : http://api.jquery.com/outerHeight/

and if your html is:

<div style="height:450px;"></div>

then you can use this to get the height:

$("#parent").css('height'); // this will give you the 450px

Upvotes: 3

Joseph
Joseph

Reputation: 119887

jQuery calculates the height, using .height(), even when there is no height setting (via CSS or otherwise) on the element.

Upvotes: 0

Travis J
Travis J

Reputation: 82337

Just like you said, with .height(), there does not need to be an actual height defined for that to be used. here is a jsfiddle showing it in action: http://jsfiddle.net/nWb5j/

Upvotes: 1

Related Questions