Absolute and Relative Units in CSS

In this lesson, we are going to summarize all the units that are available in CSS. You are probably already familiar with some of them.

Absolute units

First of all, we have the absolute units:

  • cm: Centimeters.
  • mm: Millimeters.
  • in: Inches.
  • px: Pixels.
  • pt: Points, 1pt equals 1/72in.
  • pc: Picas, 1pc equals 12pt.

These units define a fixed value, and they will not be affected by other elements ot the screen size. They are useful when you need precise control over the size of an element.

Relative units

Besides the absolute units, there are also relative units, whose values are relative to some other elements or the screen size.

  • em: Relative to the font size of the parent element. If not set, the default font size will be 16px. 2em is two times the current font size, which is 32px.
  • ex: Relative to the x-height of the current font. This is rarely used.
  • ch: Relative to the width of the character 0. The value may be different for different fonts.
  • rem: Relative to the font size of the root element, <html>. This provides a consistent base size across the entire document, and as a result, this is the most commonly used unit for fonts.
  • vw: Relative to 1% of the width of the viewport. Viewport is the visible area of the webpage, such as the browser window.
  • vh: Relative to 1% of the height of the viewport.
  • vmin: Relative to 1% of the smaller dimension (width or height) of the viewport. This ensures the element is at least visible on the screen.
  • vmax: Relative to 1% of the larger dimension (width or height) of the viewport.
  • %: Relative to the parent element.

These units adapt based on the context, and are more flexible and useful for responsive design.

How to choose the right units

Among these options, there are only 6 units that are commonly used: px, em, rem, %, vw, and vh.

  • px is often used for fine-grained, pixel-level control when you need to specify the exact size of an element.
  • em and rem are often used for font size and text spacing. em is relative to the font size of its closest parent element, and rem is relative to the document's root element.
  • %, vw, and vh are the three most popular relative units used for defining dimensions and creating layouts that adapts to either the parent element (%), or the view port (vw, and vh).

Each of these units plays a unique role in web design, providing different levels of flexibility and control depending on the layout and responsiveness requirements. To summarize, when you need responsive and flexible dimensions and layouts, use %, vw, and vh; when you are working with texts, use em and rem; when you need to define the exact size of an element, use px.