Ωmega
Ωmega

Reputation: 43673

Convert non-pixel css value to px

As some measurement parameters in css are not always in px values, how can be such non-pixel value converted to px?

Let's have

var x = $('#element').css('parameter');

and let's say that the value of such x variable is 1.2em or some other string that contains not just number, but also measurement type information (px, em, pt, cm, in, ...).

What is all-browser solution to convert such string into integer, having results in px?

Upvotes: 3

Views: 2882

Answers (2)

Ashish Maradiya
Ashish Maradiya

Reputation: 113

$("#element").css("padding","2em")
var value = parseInt($("#element").css("font-size"));
var padding = 2*value ;
console.log(padding);

Upvotes: 0

Nick Husher
Nick Husher

Reputation: 1884

You can use the built-in method getComputedStyle which will interpolate any non-px value into pixels. For example:

var el = document.getElementById('foo'); // has a relative font size

console.log(el.style.fontSize); // "5em"
console.log(window.getComputedStyle(el).fontSize); // "80px"

From there you can convert into an integer.

Example JsBin and MDN Documentation.

Upvotes: 3

Related Questions