Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS convert percent to pixels

Tags:

javascript

css

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?

like image 952
Jacek Avatar asked Jan 16 '23 17:01

Jacek


2 Answers

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)

like image 77
Oriol Avatar answered Jan 23 '23 13:01

Oriol


Use window.getComputedStyle() for this

<div style="wdith:50%">50% width</div>​​​​​​​​​​​​​

(function() {
    var div = document.getElementsByTagName("div")[0];

    console.log(window.getComputedStyle(div, null)["width"]);
}())​

fiddle

Supported by all major browsers and IE9+. For lower versions of IE have a look at currentStyle

like image 45
Andreas Avatar answered Jan 23 '23 14:01

Andreas