HTML & CSS - - By Craig Buckler

The New CSS3 Relative Font Sizing Units

It’s been more than three years since I last wrote about CSS font sizing. For a decade we were lumbered with inconsistent keywords (small, medium, large etc) and flawed fixed units (px, pt, mm). While the problems associated with px in Internet Explorer have dissipated, % and em remained the best choices — especially for responsive designs.

Fortunately, CSS3 provides us with several new alternatives…

rem

One issue encountered with percentage and em sizing is the compounding cascade conundrum! Consider this basic example…

<style>
body  { font-size: 100%; }
p, li { font-size: 0.75em; }
</style>

<p> 12px text </p>

<ul>
<li> 12px text
<ul><li> 9px text </li></ul>
</li>
</ul>

em units are relative to their parent container so nested lists have decreasing font sizes. It can be difficult to determine font sizes on complex pages — most of us use the force (lots of trial and error).

rem is similar to em except that it’s relative to the root element rather than the parent. Changing the li selector to 0.75rem will ensure all nested lists remain at 12px.

rem is available in Chrome, Firefox, Safari, Opera and IE9+. Older browsers can be supported with a fallback and you’ll probably find it easier to use absolute units, e.g.

p, li
{
  font-size: 12px;
  font-size: 0.75rem;
}

vw, vh and vmin

These new properties allow you to scale font sizes according to the viewport dimensions, i.e.

  • 1vw is 1% of the viewport width
  • 1vh is 1% of the viewport height
  • 1vmin is the smallest of 1vw and 1vh

For example, assume your browser viewport is set to 1,000 x 1,200 pixels:

  • 1.5vw = 15px font size
  • 1.5vh = 18px font size
  • 1.5vmin = min(1.5vw, 1.5vh) = 15px font size

The new units will revolutionize responsive design — text on mobile devices often appears a little large because you’re holding the device closer than a monitor.

Browser support is a little patchy but it’s coming…

  • IE10 — full support
  • IE9 — supported, but vmin is named “vm”
  • Chrome 22+ — full support
  • Safari 6 and iOS Safari 6 — full support
  • Firefox — will be implemented in version 19 (late February 2013)
  • Blackberry Browser 10 — full support

No word from Opera yet, but I suspect they’re on the case. Again, it may be advisable to use fallbacks for a few years, e.g.

p, li
{
  font-size: 12px;    /* old */
  font-size: 1.2vm;   /* IE9 */
  font-size: 1.2vmin;
}

Will you adopt any of these new font sizing units in your pages?

And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like HTML5 & CSS3 For the Real World.

Comments on this article are closed. Have a question about CSS3? Why not ask it on our forums?

Sponsors