CSS Units

Many CSS properties, like width, margin and font-size, need a number with a unit. There are two kinds of units: absolute and relative.


Absolute unit: px

A pixel (px) is a fixed size. It does not change when the screen or the parent changes. Other absolute units are pt, cm and in, which are mostly used for printing.


Relative units

UnitRelative toExample
%The size of the parent elementwidth: 50%
emThe font size of the element (or of its parent for font-size)padding: 2em
remThe font size of the root (html) elementfont-size: 1.5rem
vw1% of the viewport widthwidth: 80vw
vh1% of the viewport heightheight: 100vh
html { font-size: 16px; }

h1 { font-size: 2rem; }      /* 2 x 16 = 32px */
p  { font-size: 1.125rem; }  /* 18px */
.box { width: 50%; padding: 1em; }

Which unit should I use?

  • Font sizes: rem, so the text follows the visitor’s own font settings.
  • Widths: % or max-width with a px value, so layouts can shrink.
  • Full screen sections: vh and vw.
  • Borders and thin lines: px.
Note: A value of 0 needs no unit. Write margin: 0 and not margin: 0px.

Summary

  • px is fixed. %, em, rem, vw and vh are relative.
  • Use rem for fonts and % or max-width for flexible layouts.
  • Next: CSS Background.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.