Get computed font size for DOM element in JS
Solution 1
You could try to use the non-standard IE element.currentStyle
property, otherwise you can look for the DOM Level 2 standard getComputedStyle
method if available :
function getStyle(el,styleProp) {
var camelize = function (str) {
return str.replace(/\-(\w)/g, function(str, letter){
return letter.toUpperCase();
});
};
if (el.currentStyle) {
return el.currentStyle[camelize(styleProp)];
} else if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el,null)
.getPropertyValue(styleProp);
} else {
return el.style[camelize(styleProp)];
}
}
Usage:
var element = document.getElementById('elementId');
getStyle(element, 'font-size');
More info:
- Get Styles (QuirksMode)
Edit: Thanks to @Crescent Fresh, @kangax and @Pekka for the comments.
Changes:
- Added
camelize
function, since properties containing hypens, likefont-size
, must be accessed as camelCase (eg.:fontSize
) on thecurrentStyle
IE object. - Checking the existence of
document.defaultView
before accessinggetComputedStyle
. - Added last case, when
el.currentStyle
andgetComputedStyle
are not available, get the inline CSS property viaelement.style
.
Solution 2
Looks like jQuery (1.9 at least) uses getComputedStyle()
or currentStyle
itself when you use $('#element')[.css][1]('fontSize')
, so you really shouldn't have to bother with more complicated solutions if you're OK using jQuery.
Tested in IE 7-10, FF and Chrome
Solution 3
To overcome the 'em' problem I have quickly written a function, if the font-size in ie is 'em' the function calculates with the body font-size.
function getFontSize(element){
var size = computedStyle(element, 'font-size');
if(size.indexOf('em') > -1){
var defFont = computedStyle(document.body, 'font-size');
if(defFont.indexOf('pt') > -1){
defFont = Math.round(parseInt(defFont)*96/72);
}else{
defFont = parseInt(defFont);
}
size = Math.round(defFont * parseFloat(size));
}
else if(size.indexOf('pt') > -1){
size = Math.round(parseInt(size)*96/72)
}
return parseInt(size);
}
function computedStyle(element, property){
var s = false;
if(element.currentStyle){
var p = property.split('-');
var str = new String('');
for(i in p){
str += (i > 0)?(p[i].substr(0, 1).toUpperCase() + p[i].substr(1)):p[i];
}
s = element.currentStyle[str];
}else if(window.getComputedStyle){
s = window.getComputedStyle(element, null).getPropertyValue(property);
}
return s;
}
Pekka
Self-employed web developer and graphic designer. After-hours artist. Working from an old off-the-grid house in the Canary Islands. Not doing much here any more because the Stack Overflow I wish to build and participate in is no longer supported and the company running it has started going down a path of incomprehensible, increasingly outright evil actions. E-Mail: first name at gmx dot de
Updated on April 11, 2020Comments
-
Pekka about 4 years
Is it possible to detect the computed
font-size
of a DOM element, taking into consideration generic settings made elsewhere (In thebody
tag for example), inherited values, and so on?A framework-independent approach would be nice, as I'm working on a script that should work standalone, but that is not a requirement of course.
Background: I'm trying to tweak CKEditor's font selector plugin (source here) so that it always shows the font size of the current cursor position (as opposed to only when within a
span
that has an explicitfont-size
set, which is the current behaviour). -
Pekka over 14 yearsThis looks great, will try it out.
-
Crescent Fresh over 14 yearsBe careful,
currentStyle
andgetComputedStyle
are fundamentally different: erik.eae.net/archives/2007/07/27/18.54.15getComputedStyle
is incapable of getting the inherited style, and always computes it aspx
, whether the value was declared aspx
or not. -
Pekka over 14 yearsThanks for the caveat. Very good to know. For the job at hand it's fine, as stated above.
-
kangax over 14 yearsIt's actually
document.defaultView.getComputedStyle
, notwindow.getComputedStyle
(MDC gets it wrong, or considers its own — Mozilla — implementation only).getComputedStyle
is specified to be a member ofAbstractView
, whichdocument.defaultView
implements, and there's really no guarantee thatwindow == document.defaultView
(neither in specs, nor in practice; in fact, Safari 2.x is a good example ofwindow != document.defaultView
). It's interesting that PPK does similar mistake in getstyles article that you linked to (testingdefaultView
onwindow
). -
Pekka over 14 yearsThanks a lot for your help folks. I got it working with Firefox but am stuck with IE. If you'd like to take a look: stackoverflow.com/questions/1956573/runtimestyle-in-ie7-8
-
Pekka over 14 yearsSorted. @CMS, if I'm not mistaken you need to edit your answer to point out that
currentStyle
will accept camelized properties only (e.g. fontSize) whilegetPropertyValue
works with the original form (font-size). -
Christian C. Salvadó over 14 yearsMany thanks for the feedback guys, edited to check
document.defaultView
instead ofwindow
as @kangax points out, also added acamelize
function to get the right properties when working withel.currentStyle
, any further feedback is really appreciated! -
kangax over 14 yearsWell, it would also be a good idea to check existence of
document.defaultView
before accessinggetComputedStyle
on it. -
Vinze almost 14 yearsDoes someone know why this doesn't work with jQuery ? if I replace var element = document.getElementById('elementId'); getStyle(element, 'font-size'); by getStyle($('#elementId'), 'font-size') there is a javascript error...
-
Tim Down over 13 years@Vinze: that's because
$('#elementId')
returns a jQuery object while CMS'sgetStyle
function expects a DOM element. UsegetStyle($('#elementId')[0], 'font-size')
instead. -
Stephan over 4 yearsor more simply :
$('mySelector').css('font-size')