CSS Units of Measure

CSS has several units of measurements to express length.

Many CSS properties take a length. Some of these are: padding, margin, width, font-size, border-width etc.
You declare these properties with a number and then a unit to measure by, ie: 20px.

There are two classes of measurements, Relative and Absolute.

Relative measurement units specify a length relative to another property. Relative measurements scare better in different rendering environments.

Examples of Relative measurements:
em – Relative to the font-size of the existing element. Ie: 2em will make it two times the size of the current font. If the font size is 12px, 2em would be 24px.

p { font-size: 2em; }

rem – Relative to the font-size of the root element. rem is new with CSS3. This allows us to do relative sizing with a set base within a HTML element. 1rem by default is 16px.

The main problem with em units is that they are relative to the font size of their own element. As such they can cascade and cause unexpected results. You have to worry a lot more about nesting when using em. rem gives you a starting point for the entire document without worrying about what else modified your elements along the document tree.

body {  font-size: 14px; }
div { font-size: 1.2em; // calculated at 14px * 1.2, or 16.8px }

<body>
  <div>
    Test <!-- 14 * 1.2 = 16.8px -->
    <div>
      Test <!-- 16.8 * 1.2 = 20.16px -->
      <div>
        Test <!-- 20.16 * 1.2 = 24.192px -->
      </div>
    </div>
  </div>
</body>

Another way to size things relatively is to increase or decrease their size by percentage. A length set in percentage is based on the length of same property of the parent element. For example, if an element renders at 450px width, a child element with a width set to 50% will render at 225px

p { line-height: 120%; }

The most common way to set lengths absolutely is with screen pixels. You can set length properties with the px notation. Pixel size is slightly dependent on the resolution of the device. For screen displays, it traditionally represents one device pixel (dot). However, for printers and high-resolution screens, one CSS pixel implies multiple device pixels, so that the number of pixels per inch stays around 96.

p { width: 400px; }