The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1

200 Chapter 16


Root-Relative Units


The first new unit introduced in CSS3 is the rem, or root em. It behaves like
the em unit from CSS2.1, but instead of being relative to the font-size value
of the current element, it’s relative to the font-size value of the document
root (the html element).
Although em is quite useful, it’s not without its drawbacks, which
become most apparent when nesting elements. To illustrate the problem,
I’ll use this markup:

<ul>
<li>Western gorilla
<ul>
<li>Western lowland gorilla</li>
<li>Cross River gorilla</li>
</ul>
</li>
</ul>

and this simple style rule:

li { font-size: 2em; }

If you presume that the root font-size of the document is the common
browser default of 16px, the first li element will have a calculated font-size
of 32px (16 multiplied by 2). But the font-size of the li elements nested
inside the first would be calculated relative to the inherited value, making
them 64px (32 multiplied by 2).
This is where the rem unit becomes essential. Here’s the same code as
the previous example, only now using the rem in place of the em unit:

li { font-size: 2rem; }

Again, presuming a root font-size of 16px, the first li has a calculated
font-size of 32px. This time, however, the font-size of the nested li ele-
ments is also relative to the root value, the same as their parent. And no
matter how many nested layers down you go, that value is always relative to
the root.

Viewport-Relative Units


When building responsively, developers tend to use percentage values for
layout elements, as they scale fluidly across the range of different screen
sizes that websites need to cater to. Percentages are useful at a top level,
but—as you just saw with em units—you can run into difficulties when using
percentages with nested elements.
Free download pdf