MC Emperor MC Emperor - 3 months ago 23
Javascript Question

How to get the actual rendered font when it's not defined in CSS?

How do I get the actual font face and font size of an element when the CSS

font-face
and
font-size
properties are not defined?

For example, the JavaScript snippet

object.style.fontFamily


does not return any value. That's pretty obvious, assuming CSS hasn't applied a style to
object
anywhere. But, of course, a certain font is used to render the text, probably the system font or the webbrowser default font.

So can, for instance, JavaScript get that rendered font?

Answer

I suggest this function:

function css( element, property ) {
    return window.getComputedStyle( element, null ).getPropertyValue( property );
}

Usage:

css( object, 'font-size' ) // returns '16px' for instance

Note: getComputedStyle doesn't work in IE8.

Live demo: http://jsfiddle.net/4mxzE/