CSS Units

Modern browsers support a large number of units for sizing web page elements. In a web page, you may need to modify the size of:

  • text
  • images
  • different elements (menus, headers, etc...)

Not all units are systematically necessary, we will see in this page those that are most useful initially:

  • pixels (unit: px)
  • the em unit and especially rem
  • percentages (unit: %)
Generally, absolute units are rarely used because they do not allow elements to adapt to the user's screen size.We can add that units such as cm, mm, pt, pc are almost never used, because they do not correspond to the reality of a web page and therefore a screen display.

Accessibility

In browsers, you can define the base font size. This size will then be defined in the root element of the web page, i.e., the html tag.

Thus, a visually impaired user who would need to display text in a large size can configure their browser.

This is why we avoid using the px unit, which is an absolute unit. Text whose style is modified to be displayed at 16px will therefore be the same size on a default-configured browser and on a browser configured for a visually impaired person.
We will then prefer the rem unit.

Three practical units

Pixels (px)

Pixels represent a fixed unit corresponding to a point on the screen. It's one of the simplest units to understand. It's particularly useful for defining precise dimensions, such as text size, borders, or margins.

Example:

h1 {
  font-size: 24px; /* Fixed text size */
  margin: 10px;    /* Fixed margins around the element */
}
However, pixels do not automatically adapt to screen size or user accessibility preferences.

Percentages (%)

The percentage unit is relative to a parent container. It's ideal for creating proportional elements, especially in fluid or responsive layouts.

Example:

div {
  width: 50%; /* The element's width will be half that of its parent container */
}

Percentages are also used for properties like height, margins, or padding.


Relative units: rem (and em)

Relative units allow better adaptability, as they depend on the font size defined in the context:

difference between em and rem
  • rem (root em): relative to the font size defined on the root element (html).
  • em: relative to the font size of the immediate parent element.

Advantage of rem over em:rem is more predictable, as it only depends on the size defined at the root, while em can vary according to inheritance and nested elements.

Example:

html {
  font-size: 16px; /* Base size */
}

h1 {
  font-size: 2rem; /* 2 times the base size (32px) */
}

p {
  font-size: 1rem; /* Equal to the base size (16px) */
}

With these units, it's easier to adapt elements to different screens and text sizes, while respecting accessibility principles.