What is a CSS unit?

A CSS unit is the standard of measurement used in CSS to express the size of a specific element’s property.

Types of CSS units

1. Absolute length units

Absolute length units are fixed standards of measurement.

The size of things expressed in absolute units will never change, regardless of the medium used to display them. As such, they work best with print outputs.

Typical examples are cmcentimeters, mmmillimeters, ininches, and pxpixels.

2. Relative length units

Relative length units are dynamic standards of measurement.

The sizes of things expressed in relative units will always be dependent on another length. As such, they work best with rendering mediums, such as computer screens.

Typical examples are emelement, remroot element, %percentage, and frfraction.

em vs. rem

The difference between the em unit and the rem unit is that em scales an item relative to the element’s parent’s font size.

However, rem scales an item relative to the root element’s font size.

Example

In the snippet below, <div>’s width is set to 10em. As such, the em unit scaled the <div>'s width to 400px (10 multiplied by 40pxthe font size of <div>’s parent element (<body>)).

However, in the snippet below, <div>’s width is set to 10rem. Therefore, the rem unit scaled the <div>’s width to 200px (10 multiplied by 20pxthe font size of the root element (<html>)).

em vs. %

The difference between em and the percentage unit is that em scales an item by multiplying the element’s parent’s font size by a number.

However, % scales an item by multiplying the element’s parent’s size by a percentage.

Example

In the snippet below, <div>’s width is set to 20em. As such, the em unit scaled the <div>’s width to 600px (20 multiplied by 30pxthe font size of <div>’s parent (<main>)).

However, in the snippet below, <div>’s width is set to 20%. Therefore, the percentage unit scaled the <div>’s width to 80px (20% multiplied by 400pxthe width of <div>’s parent (<main>)).

Free Resources

Attributions:
  1. undefined by undefined