The CSS Pocket Guide: Measurements, URLs, and Color Units
In the discussion of CSS syntax in Chapter 1, you saw that the second part of each CSS declaration is a value. In this chapter, you'll explore some common units for defining sizes (<length> and <percentage>), colors (<color>), and URLs (<url>) for defining these values.
Measurements
Dimensions and other measurements, such as font-size, are not just raw numbers but a number of some specified of units of measure. CSS has quite a variety of measurement units; the most commonly used are outlined in the following sections.
Pixels (px)
img.thumbnail { width:150px
; } div { border-width:3px
; }
A pixel unit (<length>) is a fixed measurement based on the size of a common pixel.
Ems (em)
h1 { font-size:1.6em
; } /* make h1 font larger than base */ blockquote { width:20em
; } /* keep block readable */
One em unit (<length>) is a relative unit that equates to the font size of the element. When applied to the font-size property of an element, an em unit is relative to the parent element's font size. This behavior makes it useful for keeping the font size for emphasis, headers, and other tags relative to the base font sizing. It's also useful when applied to dimensions as a way to control readability and line lengths.
Points (pt)
body { font-size: 12pt
; }
Points are an absolute length–based unit (<length>) equal to 1/72 of an inch. Points can be useful when setting type sizes for print and similar media where physical measurements may be stressed. On screen and mobile media, points are approximated based on the resolution of the display and the system settings, and working with px or em units can lead to more consistent results.
Percentages (%)
.column1 { width:30%
; } /* 30% of the containing block width */ p { line-height:140%
; } /* 140% of the font-size of the element */ p.note { font-size:90%
; } /* 90% of the parent's font-size */
Percentage-based units (<percentage>) are relative to another measurement. Percentages can be greater than 100 percent. Which measurement the value relates to is defined on a case-by-case basis; the previous code lines show some examples.
Other Units of Note
Points are considered an absolute length –based units: They correspond to a physical measurement of 1/72 of an inch (approximated by the browser and device). Other absolute units include in (inches), cm (centimeters), mm (millimeters), and pc (picas, or 12pts).
Pixels and ems are relative length –based units: They are relative to some other measurement. Like em, the ex unit is relative to the size of the font (the ex-height or height of the character "x"). CSS3 has defined some other interesting relative length units such as the following: rem (relative to the font size of the root element) and vw and vh (relative to the viewport width and height, respectively). These units are just starting to be supported in previews of the next generation of browsers but are something to look forward to using.