How can I get the computed width of an element in Opera? In other browsers I can do this:
// getComputedStyle wrapper
function getStyle(element, styleProp) {
return element.currentStyle ? element.currentStyle[styleProp] :
getComputedStyle(element, null).getPropertyValue(styleProp);
}
…but this only sort of works on Opera. It returns “auto” for a lot of things instead of a useful pixel value.
Here’s a live demo that expands some text to fit in a box. It doesn’t work on Opera, because the computed width is auto instead of a px value as in other browsers.

How can I get more useful computed styles, such as the pixel width of an element, in Opera?
I realize that I can, in this case, use offsetWidth instead of getting the computed style. I appreciate the advice, but the real point of this question is that I want to know how to get computed styles in Opera where the style is actually computed in units. I don’t care about offsetWidth for the purposes of this question.
It also fails in IE <= 8
The reason is because
currentStyleandgetComputedStylework differently in this case. If you were testing forgetComputedStylefirst it would work in both Opera and IE 9-10. Opera tries to mimic IE in a lot of cases (seeinnerText vs textContent), so it hascurrentStyletoo.BUT please note that you lose your “expected” behavior if the element in question has
display:inlinein it’s style (FF, Chrome, IE), because they will report “auto” for you… except… you guessed it, in Opera which will then show you the “correct”pxwidth of the element.If you want a general purpose function you better off including a general purpose library (which as you will find are filled with edge cases you will never need). If you have a specific purpose to solve you can use a compatible replacement.
Computed style isn’t really useful for you in this case. What you need is probably
clientWidth,offsetWidthorscrollWidthdepending on your needs. They differ mainly in whether you want to include padding,border,marginand/or clipped areas (in case of horizontally overflowing content).They are supported even on ancient browsers like IE 6, in fact these properties were first introduced by MS back in the first browser war (just like
innerHTML).You can read more about them by googling with MSDN or MDN.