What is the difference between the three units mentioned in this exercise: pixels, ems, and percentages? How do I know which units to use?


#1

Question

What is the difference between the three units mentioned in this exercise: pixels, ems, and percentages? How do I know which units to use?

Answer

A pixel is an absolute unit of measure equal to 1/96 of an inch whereas ems and percentages are both relative units of measure. An em is a typographical unit which is relative to the font-size of an element. When dealing with ems it is important to realize that the font-size of an element is often inherited from an ancestor element. For example:

	<p>Test</p>
</div>```

```div {
Font-size: 16px;
}

p {
	Font-size: 1.25em;
}```

Our `<p>`element inherits a font-size of 16px from its parent `<div>` and then multiples this value by its own `font-size` value of 1.25em to get a font size of: 16 * 1.25 = 20px. Due to the compounding and often difficult to track nature of inheritance, developers often use `rems` or root ems in place of ems. Rems are determined based on the `font-size` of the `html` element. If `font-size` is not defined on the `html` element, the browser’s default `font-size` is used instead (usually 16px).

The percentage unit is depended on the specific property in question. For example, the `width` and `height` properties define percentages relative to the `width` and `height` of a parent element whereas the `font-size` property defines percentages relative to the `font-size` of a parent element. 

There are pros and cons of each unit but one major advantage of using relative units is that they lend themselves more naturally to responsive design. Relative units are flexible and scalable whereas pixels are not.

As a very general rule of thumb, for responsive designs use ems or rems for typography and percentages to specify element sizes. Please note, there are lots of opinions surrounding this topic. Experiment with different units so you can get a first hand feel for the pros and cons of each!