CSS Units
When specifying numerical or length values for CSS properties such as width or font-size you have a choice of different units. The 3 most used ones are pixels, relative values and percentages.
Pixels
Pixels are the tiny dots that make up your computer screen and are the most accurate unit you can use for this medium. If you set a width to 100 pixels it will be displayed exactly like that, no more and no less. To set values in pixels you simply append a px right after the value.
CSS pixel unit:
- img {width:100px}
Relative values
Relative values are often used for font-size, though they can be used for any other numerical property, too. They are relative to the current element and are set by appending an em. 1em always uses the current value unchanged, 2em uses the double and 0.5em uses half of it. (Technically em means relative to the width of the m character in the current font)
CSS relative value unit:
- body {font-size:13px}
- p {font-size:2em}
Above code sets the font-size to 13 pixels for the body element. The paragraph elements inside the body use a relative value of 2em, thus doubling the value to 26 pixels.
If we use 1.9em instead, the paragraph value will result in 24.7 pixels. Because a computer screen can only display whole pixels the web browser will attempt to round the value to either 24 pixels or 25 pixels which can sometimes cause inconsistencies between browsers.
Percentages
Percentages work pretty much the same way as relative values. 100% takes the current value unchanged, 200% doubles it and so on. Percentages are set by appending a %.
CSS percentage unit:
- body {font-size:13px}
- p {font-size:200%}
Zero
When a value is set to zero there's no need to state a unit.
CSS value zero:
- p {border-width:0}
Other units
There are some more rarely used units such as pc (picas), cm (centimeters), mm (millimeters), in (inches) and pt (points).
Usage guidelines
1. Relative values for fonts
A website ought to be flexible and resizable, including fonts (by holding down the Ctrl key and moving your mouse wheel). Some older versions of Internet Explorer refuse to resize fonts if you specify the font-size in pixels. Use a relative value instead. 76% for the body font and em for all other fonts is a commonly used technique for getting consistent fonts across all browsers.
2. Pixels only if needed
The general rule of thumb is to use relative values and percentages wherever possible to ensure a flexible layout across all media. Though pixels are ok if you need to position things very precisely on-screen.