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?
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/
console.log(
getComputedStyle(document.getElementById('test'), null)
.getPropertyValue('font')
)
#test {
font-family: fantasy, cursive;
}
<div id="test">Lorem ipsum dolor sit font-face</div>