English translation of a Persian article from the WebTarget archive. The date above is the original publication date. Some advice, especially technical details, may be outdated.
CSS is a powerful tool for shaping web pages. This tutorial is part of a series exploring straightforward, useful CSS techniques. It looks at how relative units can make font sizing more flexible.
Relative font sizes
When you set a font size in em, it is calculated
from the parent element’s font size. This lets text sizes relate
to their surrounding context and respond to the reader’s browser
settings.
Fixed sizing can be useful when the expected output is known,
but the original tutorial favoured relative sizes to avoid
differences in older browsers, particularly Internet Explorer.
To convert a pixel size to em, divide the desired
size by the parent’s font size in pixels. The example below
assumes a parent size of 16px; 1em is not always
16px.
CSS (syntax)
16px=1em
pixels/16=em
h1 {font-size:2.5em;} /* 40px/16=2.5em */
h2 {font-size:1.875em;} /* 30px/16=1.875em */
p {font-size:0.875em;} /* 14px/16=0.875em */
Another technique used in the original article is to set the
body font size to 62.5%. When the browser’s default font size is
16px, this makes the body’s font size 10px, simplifying
conversions between pixels and ems. In the example, a paragraph
sized at 1.2em becomes 12px.
Technical clarification: the result depends on
the user’s default font size, and nested em-based sizes can
compound. Modern browsers can zoom pixel-sized text too; this
historical technique does not guarantee identical rendering
across browsers.
CSS
body {
font-size: 62.5%; /* font-size 1em = 10px */
}
p {
font-size: 1.2em; /* 1.2em = 12px */
}
The following examples show the arithmetic after establishing that 10px base. Use these figures to understand the conversion, rather than as a recommendation to make all text this small.
CSS
h1 {
font-size: 1.6em;
} /* 16px/10=1.6em */
h2 {
font-size: 1.4em;
} /* 14px/10=1.4em */
p {
font-size: 1.2em;
} /* 12px/10=1.2em */