How To Get Font Size in HTML

Mark Walsh picture Mark Walsh · Mar 4, 2013 · Viewed 83.6k times · Source

I was reading a question on here trying to get the font size of a text. The answer they gave was to get the pixel size using a measure method. All i want to be able to do is get the font size value so i can change it.

For example:

var x = document.getElementById("foo").style.fontSize;
document.getElementById("foo").style.fontSize = x + 1;

This example does not work though these two do

  1. document.getElementById("foo").style.fontSize = "larger";
  2. document.getElementById("foo").style.fontSize = "smaller";

The only problem is that it only changes the size once.

Answer

Paul Armstrong picture Paul Armstrong · Mar 4, 2013

Just grabbing the style.fontSize of an element may not work. If the font-size is defined by a stylesheet, this will report "" (empty string).

You should use window.getComputedStyle.

var el = document.getElementById('foo');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style); 
// now you have a proper float for the font size (yes, it can be a float, not just an integer)
el.style.fontSize = (fontSize + 1) + 'px';