Getting element width without padding in Internet Explorer

I want the images on my site to fit the size of their containing element, so I have this:

if (userHasMicrositePhoto) { var width = $('micrositePhotoDiv').getComputedSize().width; $('micrositePhoto').src = "flash/userImage.ashx?type=micrositePhoto&id=" + userId + "&width=" + width; } 

My userImage.ashx handler file returns the image specified by the identifier, scaled to the width specified as the parameter.

This works fine in firefox, chrome and co, but it doesn't work in Internet Explorer - the image is too large. I think this is because .getComputedSize().width Width reports a width that includes the size of the indents (but at the border or markup) in Internet Explorer, but returns only the useful area in other browsers. As a result, the width specified by Internet Explorer is too large.

I cannot find other fields available for .getComputedSize() , which allows me to find the β€œactual” width in Internet Explorer. I tried using .getComputedStyle() to get the padding so that I could subtract it from the total width, but this returns a string and I style the micrositePhotoDiv element as padding: 0.75em , so this does not work.

What do I need to do to get the right width in Internet Explorer?

+4
source share
2 answers

You can make padding 0, but checking computed styles for sizes and positions is often tricky and it's hard to align acreoss browsers.

Use offsetWidth or clientWidth instead in all browsers.

0
source

jQuery width() does just that (see jQuery source code ).

As you saw, usually getComputedStyle returns the width in pixels, so you can often do (except for the old IE):

 var width = parseFloat(window.getComputedStyle(elem).width); 
+1
source

All Articles