Changing font size with JavaScript

Published:
May 25, 2007 @ 3:14 am
Category:
JavaScript
Author:
Chris Wheeler

As you’ve probably noticed, this site has three increasingly large ‘A’ characters in the top right of the design. These enable you to quickly increase the size of the font on the page, to make articles and long sections of text easier to read.

I’ll explain briefly how they work, and how to set them up.

Setting up your pages

To be able to scale font sizes you must make sure all of your CSS ‘font-size’, ‘line-height’ and other font-related measurements are specified in ‘em’ units, and NOT in ‘px’ units.

Internet Explorer will not allow ‘px’ (pixel) based font sizes scaled, which actually makes sense - as pixel measurements are by definition an absolute measurement, set by the users screen resolution. ‘em’ measurements on the other hand, are relative - and can therefore be scaled.

The other feature of ‘em’ measurements which we will make use of, is that they are relative to the size of their parent element. This means that we only have to change the size of the font on the <body> element, and all child elements font sizes will change.

The HTML/JavaScript

<span class="fontsizes">
  <span class="fontsmall">
    <a href="#" onclick="body.style.fontSize='8px'">A</a>
  </span>
  <span class="fontmedium">
    <a href="#" onclick="body.style.fontSize='10px'">A</a>
  </span>
  <span class="fontlarge">
    <a href="#" onclick="body.style.fontSize='14px'">A</a>
  </span>
</span>

The HTML/JavaScript above shows the three ‘A’ characters, and triggers a slightly different onclick event for each, setting the size of the font on the body element to a different size for each. Most browsers use a default size of ‘10px’ - which is the ‘medium’ font in this case. I’ve chosen 8px for the small font, and 14px for the large font, but you can use whatever suits your needs.

The CSS

.fontsizes {
  color: #ffffff;
  line-height: 34px;
  font-size: 10px;
}    

.fontsmall {
  font-size: 12px;
}    

.fontmedium {
  font-size: 20px;
}    

.fontlarge {
  font-size: 28px;
}

The ‘line-height’ is set to 34px, which is equal to that of the large ‘A’.

You may be thinking - ‘Why are the font sizes specified in ‘px’ here?’ - well, we don’t want these characters to change size when the user changes the font size. An alternative would be to use images instead of text characters, to ensure that no browsers scale these characters.

If you want to, you could use JavaScript to write the HTML code to the page. That way, the user will only see the three ‘A’ links if they have JavaScript enabled.