HTML and CSS Reference
In-Depth Information
Figure 11-3 A version of the Cool Shoes & Socks page viewed in Opera Mobile Emulator with the body font increased
to 1.2 em.
Percentages Versus Ems
If relative units, such as ems, work in the same way as percentages, why choose ems?
When you specify a font-size using percentages or ems, 1 em is the equivalent of 100%, 0.5 em is the equivalent
of 50%, and so on. Ems and percentages work in the exact same way when applied to font-size . However, when
used on other properties such as padding and margin , they differ.
Ems are always relative to an element's font-size , whereas percentages are relative to another value, such as the
height and width dimensions of an element. Consider the following CSS as an example:
div {
font-size: 16px;
padding-left: 1em;
width: 200px;
The calculated padding-left is 16 px because 1 em is relative to the font-size multiplied by one, which is
16 px. A padding-left of 2 em creates a calculated padding-left of 32 px and so on.
div {
font-size: 16px;
padding-left: 100%;
width: 200px;
In this example, the padding-left is changed to a percentage, so it relates to the width of the element instead,
and the calculated padding-left is therefore 200px.
Because properties such as padding and margin better relate to the size of text, it is best to use ems for font-
size . When I scaled up the font size between Figure 11-2 and Figure 11-3, the padding and margins scaled also,
aiding the readability of the page.
When working with relative units and calculated values, rather than doing all of the calculations yourself, you can
use your browser's web developer tools to find the calculated value of any element. Please refer to the sidebar
“Working with Relative Units” in Chapter 4.
You may also like to refer to Chapter 4's description of the Rem unit, which always inherits font-size from the
<html> element, making dealing with inheritance easier. Unfortunately, at the time of writing, Rem doesn't have
enough browser support to make it useful in a real-world website. It will almost certainly be the unit used for font-
size in the future though.
Search WWH ::

Custom Search