Search code examples
javascriptjqueryheightpixel

Why does jQuery only return integer height if setting a double value clearly renders differently?


I've got an image that is 924px in height. The image has been created to look appropriate at this height. Stretching it is not desireable.

Ontop of this image, I need to overlay a variable number of same-height div elements. In this particular instance I need to overlay 88. As such, the math is pretty clear:

924 / 88 = 10.5

Each div element must be 10.5 pixels in height to properly overlay my image.

Visually, everything looks great! I have 88 elements and they're all 10.5 pixels in height. If I set their height to 11px or 10px I see visual differences.

However, using jQuery:

$('div').height();  // 10
$('div').css('height'); //10px

?? Huh? They're clearly 10.5 pixels in height, not 10. If I dig into the element's style property -- I see 10.5 pixels.

What's going on? Can I get jQuery to play nice with double values for height/width? Why is it so opposed?


Solution

  • Using jquery.height() actually converts it to the actual amount of pixels it is taking up on the screen.

    You may find, if you iterated through every div on your page a mixture of height 10's and 11's, since you can't render something on only half a pixel, to actually render things that take half a pixel you would need to decide whether it will take a pixel or not. The browser will alternate between which divs do and don't to try and get the best possible result.