JQuery.width () and .height () weird behavior

Why in the following code .hight () returns 95, not 100, and .width () returns 200, as expected? I am working 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 (), as well as .innerWidth () and .innerHeight (), but none of them return the expected result: code example

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

Can anyone explain this behavior?

+6
javascript jquery html css
source share
3 answers

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

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

.outerHeight( [ includeMargin ] )

includeMargin - a logical indication of whether the margin should be included in the calculation.

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

.innerHeight()

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

Edit: The height () setting for the td element is adjusted to fit the default fill (1 pixel). The calculated dimensions are actually ...

alt text
(source: wordofjohn.com )

To avoid these problems, you should set the default indent to 0px.

 table td { padding: 0; } 

Edit 2: This seems to be a browser issue (maybe something related to the rendering method to calculate the size of the table). The effects of this behavior will vary by browser. You should find an alternative solution without using tables.

+7
source share

I cannot explain this behavior better than John, but since this browser contradiction still exists (at least for those who cannot upgrade the jQuery version), I thought I would share a workaround for this problem.

Using the HTML DOM properties clientHeight and clientWidth are apparently compatible with most browsers.

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

It is also likely that you can use offsetHeight / offsetWidth instead, depending on what you need.

+1
source share

I am not sure about this .. I also find this rather strange. This is my guess.

The border eats up the actual height and is ignored by jquery when calculating the height

0
source share

All Articles