This chapter covers
- The versatility of relative units
- How to use ems and rems, without letting them drive you mad
- Using viewport-relative units
- An introduction to CSS variables
When it comes to specifying values, CSS provides a wide array of options to choose from. One of the most familiar, and probably easiest to work with, is pixels. These are known as absolute units; that is, 5 px always means the same thing. Other units, such as em and rem, are not absolute, but relative. The value of relative units changes, based on external factors; for example, the meaning of 2 em changes depending on which element (and sometimes even which property) you’re using it on. Naturally, this makes relative units more difficult to work with.
Developers, even experienced CSS developers, often dislike working with relative units, the notorious em included. The way the value of an em can change makes it seem unpredictable and less clear-cut than the pixel. In this chapter, I’ll remove the mystery surrounding relative units. First, I’ll explain the unique value they bring to CSS, then I’ll help you make sense of them. I’ll explain how they work, and I’ll show you how to tame their seemingly unpredictable nature. You can make relative values work for you, and wielded correctly, they’ll make your code simpler, more versatile, and easier to work with.