2 Working with relative units

 

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 custom properties

When it comes to specifying length 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 a type of absolute unit; that is, 5 px always means the same thing. Some 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.

Definition

Length is the formal name for a CSS value that denotes a distance measurement. It’s a number followed by a unit, such as 5px. Percentages are similar to lengths, but strictly speaking, they’re not considered lengths.

2.1 The power of relative units

2.1.1 The rise of responsive design

2.2 Ems and rems

2.2.1 Using ems to define font-size

2.2.2 Using rems for font-size

2.3 Stop thinking in pixels

2.3.1 Setting a sane default font size

2.3.2 Making the panel responsive

2.3.3 Resizing a single component

2.4 Viewport-relative units

2.4.1 Selecting from the newer viewport units

2.4.2 Using viewport units for font size

2.5 Unitless numbers and line-height

2.6 Custom properties (aka CSS variables)

2.6.1 Changing custom properties dynamically

2.7 Summary

sitemap