Set Font Size With Em

To allow users to resize the text (in the browser menu), many developers use em instead of pixels. The em size unit is recommended by the W3C. 1em is equal to the current font size. The default text size in browsers is 16px. So, the default size of 1em is 16px. The size can be calculated from pixels to em using this formula: pixels/16=em. In this example, the text size in em is the same as the previous page which is done in pixels. However, with the em size, it is possible to adjust the text size in all browsers.

HTML file: Displayed by browser:
<style>
h1 {
    font-size: 2.5em; /* 40px/16=2.5em */
}
h2 {
    font-size: 1.875em; /* 30px/16=1.875em */
}

p {
    font-size: 0.75em; /* 12px/16=0.75em */
}
</style>
<body>
<h1>Default H1 heading.</h1>
<h1 class="demo">H1 heading of 2.5em.</h1>
<h2>Default H2 heading.</h2>
<h2 class="demo">H2 heading of 1.875em.</h2>
<p>This is a default paragraph.</p>
<p class="demo">This is a paragraph of 0.75em.</p>
</body>

Default H1 heading.

H1 heading of 2.5em.

Default H2 heading.

H2 heading of 1.875em.

This is a default paragraph.

This is a paragraph of 0.75em.

The reason you should use em, rather than pixels, is because it is responsive and scales according to screen size. Meaning, if you have em measurements throughout your websites, the font-sizes are relative to the font-size you specify in the body element of the css stylesheet. Change that, and it change the font sizes throughout the website! Otherwise, you have a lot of work ahead of you to change pixels sizes.

Also, there is still a problem with older versions of IE. The text becomes larger than it should when made larger, and smaller than it should when made smaller.

Back button Table of Contents Next button