Javascript – CSS convert percent to pixels

cssjavascript

I have "div" element with specified width and height expressed in percents in CSS.
I would like to get by JS script its width and height expressed in pixels. It's even possible?

Best Answer

You can use

el.clientHeight;
el.clientWidth;

(elis a reference to the element)

Demo

Note those properties were first introduced in the MS IE DHTML object model. More recently they were standardized in CSSOM View Module, W3C Working Draft 22 February 2008.

Those properties were widely supported. However, it's possible than an old non-MS compliant browser doesn't support them. In those cases, you can use getComputedStyle:

function findSize(el, size) {
    /* size must be 'width' or ' height' */
    return window.getComputedStyle
        ? getComputedStyle(el,null).getPropertyValue(size)
        : el['client'+size.substr(0,1).toUpperCase() + size.substr(1)] + 'px';
}
findSize(el, 'width');
findSize(el, 'height');

Demo

Browser support of getComputedStyle and clientHeight/clientWidth way is at least:

                 | IE  | Firefox | Chrome | Safari | Opera
-----------------|-----------------------------------------
getComputedStyle | 9   | <=3     | 1      | <=4    | <=10
client           | <=5 | <=3     | 1      | <=4    | <=10

(<=n means that it's supported at least from version n, but I couldn't test previous versions)