AkiVaMu Just tiny things come to mind...

px, em and rem

In HTML/CSS, when setting font-size, we have several options to specify unit. We will inspect some standard units.

Fixed units

px

px is pixel - the smallest unit in your screen resolution. Example:

font-size: 16px
  • Fixed unit: 16px is 16 pixels in the screen.
  • Pixel-perfect: no rounding, no anti-aliasing.

pt

pt is point - the smallest unit in your print media (paper…)
pt is more about physical size. e.g. your printer has resolution 72dpi, means 72 dots per inch.

Example:

font-size: 16pt
  • Fixed unit: just like pixel.

Relative units

%

% is relative unit compared to current parent size.

Example this page:

#parent {
  font-size: 16px
}

#child {
  font-size: 50%
}


<div id='parent'>
  <p id='child'>Hello</p>
</div>

Then the child’s font-size would be 50% of 16px is 8px

  • Relative unit: scalable to parent size.

em

Similar to %, but in decimal form.

Example:

100% = 1em
50%  = 0.5em
150% = 1.5em
  • Relative unit: scalable to parent size.

rem

rem is root em. It’s also relative unit, but relative to the root, not to its direct parent.

Example this page:

html {
  font-size: 10px
}

#parent {
  font-size: 16px
}

#child {
  font-size: 1rem
}


<div id='parent'>
  <p id='child'>Hello</p>
</div>

The root (html) has size 10px.
The parent has size 16px.
The child has size 1rem.

So 1rem means 100% of root’s size: 100% x 10px = 10px.
child size is 10px.

Choosing unit

Fixed units

Pros:

  • Pixel perfect
  • Straight forward

Cons:

  • Manually configure for difference screen resolution.
  • Nightmare when refactoring size: You have to resize all components manually.

Relative units

Pros:

  • Responsiveness to difference screen size.
  • Easier when refactoring size

Cons:

  • Not pixel perfect

Benefits of em and %

  • It’s relative to direct parent unit
  • Complicated when calculate size for nested levels, something like 50% of 80% of 100%

Benefits of rem

  • It’s relative to single root component
  • Easier when sizing deep nested components as it just refers to single root size