Summary Table

Unit Relative To Best For
px Device Screen Fixed-size elements, border, box-shadow.
rem Root (<html>) font-size Modern standard. font-size, margin, padding, most layout values.
em Parent element’s font-size Sizing elements relative to their own font-size (e.g., padding on a button).
vh/vw Viewport height & width Full-screen sections, elements sized relative to window height or width.
% Parent element’s size Responsive layouts, sizing elements inside a container.

Modern Best Practice

For most projects, a good strategy is:

  1. Use rem for font sizes and spacing (margin, padding).
  2. Use px for tiny, non-scalable values like border widths.
  3. Use %, vw, or vh for high-level layout containers.
<div style="font-size: 1.2rem;">
  <!-- Computes to 1.2 * 16px = 19.2px -->
  <div style="font-size: 1.2em;">
    <!-- Computes to 1.2 * 19.2px = 23.04px -->
    Some text.
  </div>
</div>

1. Absolute Units

Absolute units are fixed and do not change based on any other element’s size or screen settings. The most common absolute unit is the pixel (px).

px (Pixels)


2. Relative Units

Relative units are flexible because they are measured in relation to another value. This makes them ideal for building responsive and accessible websites.

rem (Root em)