CSS Length Units Font size with rem


Example

CSS3 introduces a few new units, including the rem unit, which stands for "root em". Let's look at how rem works.

First, let's look at the differences between em and rem.

  • em: Relative to the font size of the parent. This causes the compounding issue
  • rem: Relative to the font size of the root or <html> element. This means it's possible to declare a single font size for the html element and define all rem units to be a percentage of that.

The main issue with using rem for font sizing is that the values are somewhat difficult to use. Here is an example of some common font sizes expressed in rem units, assuming that the base size is 16px :

  • 10px = 0.625rem
  • 12px = 0.75rem
  • 14px = 0.875rem
  • 16px = 1rem (base)
  • 18px = 1.125rem
  • 20px = 1.25rem
  • 24px = 1.5rem
  • 30px = 1.875rem
  • 32px = 2rem

CODE:

3
html { 
  font-size: 16px; 
}

h1 { 
  font-size: 2rem;          /* 32px */
}

p { 
  font-size: 1rem;          /* 16px */ 
}

li { 
  font-size: 1.5em;         /* 24px */
}