Mike Mike - 1 year ago 44
CSS Question

jQuery.height() is setting more height than specified in the parameter

I have 2 smaller divs and one large div. I need to adjust the

of larger div to be equal to the sum of heights of both divs, plus the
vertical margin between them. Here's what I do:

<div id="team-container">
<div id="block1">Block 1</div>
<div id="block2">Block 2</div>
<div id="team-details"></div>

$("#team-container > div").on("click", function(){
var contentHeight = $("#block1").height() + $("#block2").height() + 20;
// 20 is for vertical margin
// if I console log the heights of block divs, it's 263px for certain width, so the total becomes 546, which is correctly logged if I console log contentHeight variable.
console.log( contentHeight ); // outputs 546
$("#team-details").height( contentHeight );
//if I check now by inspecting element, I can see the height has been set to 606px. Why is it so? And on the page also, the larger div is taller than the two smaller divs put together vertically.

So, the problem is that if I call
.height( 546 );
, it does not set height to 546px but sets it to 606px. But if I set height using css i.e.
.css('height', '546px');
, it works fine and height is set to exactly 546px.

Answer Source

jQuery's height function is actually very smart, and does a lot of calculations behind the scenes, regarding borders, padding margin and so on.

Consider using $("#team-details").css('height', contentHeight + 'px');. This is a more direct approach, and if you're doing your own calculation, it might fit you better in this case.

By the way, the + 'px' is actually not needed. From the jQuery documentation:

When calling .height(value), the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit

And from the css function documentation (http://api.jquery.com/css/#css-propertyName-value):

When a number is passed as the value, jQuery will convert it to a string and add px to the end of that string. If the property requires units other than px, convert the value to a string and add the appropriate units before calling the method.

And one more thing, if you'd like to further understand how the height function works, you can check it out here: https://github.com/jquery/jquery/blob/master/src/css.js in line 333 to line 353. As you can see, it calls the augmentWidthOrHeight function, that does some serious calculations and jQuery magic.