views:

437

answers:

3

This is my first post, so please go easy on me. I'm sure I'm doing everything wrong. However, I couldn't find any posts that answered the question above.

I use jQuery. I'm trying to find a way to get the current width and height of a DIV element, even if they're set to "auto". I've found many ways to do this, but no method returns the same width in IE. It is important that this method is cross-browser, as it will break the layout of the page if different numbers are returned in different browsers.

.width() and .height() do not work because in IE, padding is subtracted (e.g. width() returns 25 where width is 30 and padding is 5).

.outerWidth() and .outerHeight() are not consistent either. While they work IE (believe it or not) in FF, the padding is added again to the full width (e.g. outerWidth() returns 110 in FF where width is 100px and padding is 10px).

Is there any way out of this mess without writing complex browser checks? Thanks!

+1  A: 

jQuery should be abstracting any of these browser problems away.

See what values you get from these (assuming using Firebug or some kind of console).

var $element = $('#my-element');

console.log($element.height());

console.log($element.outerHeight());

console.log($element.css('padding-top'));

console.log($element.css('padding-bottom'));

Are they always returning consistent values?

You can also pass true to outerHeight() to get it to include the margin too.

alex
+5  A: 

It sounds to me that you need to add a DOCTYPE to your page to force IE into "standards compliant" rather than "quirks" mode. See Quirks mode and strict mode.

Also see width():

alt text

and outerWidth():

alt text

cletus
Amazing advice! I've spent all day on this and you solved it in 10 seconds. DOCTYPE actually caused width() and height() to work perfectly in ALL browsers. Thank you so much. I would have never figured that out. Apparently I don't have enough reputation to up-vote you, so I'll just thank you over and over. If I had any money I would pay you! =]
You may not be able to up-vote, but you can check @cletus' answer as the accepted one.
sberry2A
@thinktank: no worries. Box model inconsistencies is a problem that comes up here a lot. Everyone needs to learn it once. :) BTW you can accept an answer even without upvoting it if it answers your question.
cletus
Thanks, @cletus / @sberry2A, I accepted the answer.
A: 
David Semeria