Trusted answers to developer questions

What is a CSS unit?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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>)).

RELATED TAGS

css
units
html
code

CONTRIBUTOR

Oluwatobi Sofela
Attributions:
  1. undefined by undefined
Did you find this helpful?