Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .width() and .height() strange behaviour

Why in the following code .height() returns 95 rather than 100, while .width() returns 200 as expected ? I work with Firefox 3.6.3.

HTML:

<table><tr>
   <td id="my"></td>
</tr></table>
<div id="log"></div>

CSS:

#my {
   border: 5px solid red;
}

JS:

$("#my").width(200).height(100);
$("#log").append("Width = " + $("#my").width() + "<br />");
$("#log").append("Height = " + $("#my").height());

I tried .outerWidth() and .outerHeight() and also .innerWidth() and .innerHeight(), but none of them returns the expected result: code example

But, if I set position: absolute it looks much better !

Can anyone explain this behavior ?

like image 614
Misha Moroshko Avatar asked May 18 '10 15:05

Misha Moroshko


2 Answers

There are a few jQuery methods for calculating height and width. Try using outerHeight()

Excerpt from jQuery Docs: http://api.jquery.com/outerHeight/

.outerHeight( [ includeMargin ] )

includeMargin - A Boolean indicating whether to include the element's margin in the calculation.

http://api.jquery.com/innerHeight/

.innerHeight()

This method returns the height of the element, including top and bottom padding, in pixels.

Edit: Setting height() on the td-element is adjusted to include the default padding (1px). The computed dimensions of are actually...

alt text
(source: wordofjohn.com)

You should set the default padding to 0px to avoid these issues.

table td {
    padding: 0;
}

Edit 2: It appears to be a browser issue (probably something related to the rendering engine's method of calculating a table's dimensions). The effects of this behavior will vary across browers. You should find an alternate, table-less, solution using divs.

like image 191
John Himmelman Avatar answered Oct 11 '22 19:10

John Himmelman


I can't really explain this behaviour better than John, but since this browser inconsistency is still around (at least for those who can't upgrade jQuery version) I thought I would share a workaround for this problem.

Using the HTML DOM properties clientHeight and clientWidth seems to be consistent over most browsers.

$("#my").width(200).height(100);
$("#log").append("Width = " + $("#my").attr("clientWidth") + "<br />");
$("#log").append("Height = " + $("#my").attr("clientHeight"));

It's also likely that you may want to use offsetHeight/offsetWidth instead, depending on what you need.

like image 42
user2257275 Avatar answered Oct 11 '22 19:10

user2257275