Converting worded CSS values to numerical

129 views Asked by At

When I call window.getComputedStyle() on an element and try to get a property such as lineHeight, which can have both worded and numerical values, is there a way or a different function that will return a numerical value every time?

My line-height example refers to the normal keyword. Other examples include font weights and border widths. All these use keywords but map to numerical values.

2

There are 2 answers

4
Alex W On

If you are referring to the fact that the return value can contain px or other units, you can use the parseInt function:

function getTheStyle(elem,property)
{
    var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue(property);
    return parseInt(theCSSprop);
}

var element = document.getElementById('test');
alert(getTheStyle(element,"height"));

Here's a fiddle. Instead of returning 100px it returns 100

You can extract the units like so:

var str = "100em";
var matches = str.match(/([a-z]+)$/gi);
alert(matches);

fiddle

Edit:

Apparently, normal can be set to a "reasonable" value by the user agent, and is font-specific, where the spec recommends it be between 1.0 and 1.2. So you would probably be better off calculating it's height property.

normal

Tells user agents to set the used value to a "reasonable" value based on the font of the element. The value has the same meaning as <number>. We recommend a used value for 'normal' between 1.0 to 1.2. The computed value is 'normal'.

Here's an in depth blog post about it.

0
Niet the Dark Absol On

No. Because there is not always a mapping.

Example:

<div></div>

JS:

alert(getComputedStyle(document.body.children[0]).width);
// alerts "auto"

Now... what numeric value would satisfy that?