Skip to main content

CSS Relative Units

A relative unit gets its length from another length property, for example on the parent element, the root element, or the viewport.

Such units adapt better when screens come in different sizes.

Tip: For scalable, responsive websites, em and rem are excellent choices!

The viewport is the size of the browser window. With 1vw equal to 1% of its current width, a viewport 500px wide makes 1vw equal to 5px.

Relative units table

The table lists the CSS relative units along with the reference that each one is measured against.

index.html
<table>
  <tr>
    <th>Unit</th>
    <th>Description</th>
  </tr>
  <tr>
    <td>em</td>
    <td>Relative to the font-size of the parent element</td>
  </tr>
  <tr>
    <td>rem</td>
    <td>Relative to the font-size of the root HTML element</td>
  </tr>
  <tr>
    <td>vw</td>
    <td>Relative to 1% of the width of the viewport. 100vw = full width of the viewport</td>
  </tr>
  <tr>
    <td>vh</td>
    <td>Relative to 1% of the height of the viewport. 100vh = full height of the viewport</td>
  </tr>
  <tr>
    <td>vmin</td>
    <td>Relative to 1% of viewport's smaller dimension</td>
  </tr>
  <tr>
    <td>vmax</td>
    <td>Relative to 1% of viewport's larger dimension</td>
  </tr>
  <tr>
    <td>%</td>
    <td>Relative to the size of the parent element</td>
  </tr>
  <tr>
    <td>fr</td>
    <td>A fractional unit. 1fr equals 1 part of the available space</td>
  </tr>
  <tr>
    <td>ch</td>
    <td>Relative to width of the "0" (zero) character</td>
  </tr>
</table>

Set Font Size With Em

For em, the reference is the parent element's font size. So 2.5em comes to 40px under a parent with a 16px font size.

The headings in the example below match the sizes from the earlier pixel example, but with em users can change the text size in their browser settings.

Example

Font sizes given in em:

Prompt
Create a page that sets the base font size on the body to 16px, then uses em units to set h1 to 2.5em (40px), h2 to 1.875em (30px), and p to 1em (16px). Include sample headings and a paragraph to show the sizes.
Output: complete HTML page

Set Font Size With Rem

For rem, the reference is the font size of the root HTML element (<html>).

An em value follows its parent element's font size, but a rem value always looks to the <html> element, no matter where it appears in the document. Scalable, responsive designs benefit greatly from this: change the font size on <html>, and everything sized in rem units scales together across the whole page.

Most browsers give the <html> element a default font size of 16px. That makes 1rem equal to 16px, unless your CSS overrides it.

Example

Font sizes given in rem:

Prompt
Create a page that sets the root html element font size to 16px, then uses rem units to set h1 to 2.5rem (40px), h2 to 1.875rem (30px), and p to 1rem (16px). Include sample headings and a paragraph to show the sizes.
Output: complete HTML page