1. CSS Basics

CSS Units (px, em, rem, %, vh, vw)

What are CSS Units?

CSS units define the size of properties like width, height, padding, margin, font-size, etc. CSS uses two types of units:

  • Absolute Units
  • Relative Units

Absolute Units

Absolute units are fixed and do not change based on other elements. The most commonly used absolute unit is px.

1. px (pixels)

  • A pixel is a dot on the screen.
  • px gives precise control over size.
  • Does not scale with screen size or user settings.
h1 {
  font-size: 24px;
}

Relative Units

Relative units scale based on the size of another element or the browser viewport. These are better for responsive design.

2. em

  • Relative to the font-size of the parent element.
  • 1em equals the current font size of the parent.
  • If the parent has font-size: 16px, then 1em = 16px.
p {
  font-size: 1.5em; /* 1.5 × 16px = 24px */
}

Nested em values can multiply and cause unexpected results.

3. rem (root em)

  • Relative to the font-size of the root (html) element.
  • 1rem = font-size of <html>, usually 16px by default.
html {
  font-size: 16px;
}

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

More predictable than em.

4. % (percentage)

  • Relative to the size of the parent element.
  • Used for width, height, padding, margin, font-size, etc.
div {
  width: 50%; /* 50% of its parent’s width */
}

5. vw (viewport width)

  • 1vw = 1% of the viewport width
  • Viewport = the visible part of the browser window
div {
  width: 100vw; /* 100% of the browser width */
}

6. vh (viewport height)

  • 1vh = 1% of the viewport height
section {
  height: 100vh; /* full height of the visible screen */
}

Other Viewport Units (less common but useful)

  • vmin = 1% of the smaller between viewport width and height
  • vmax = 1% of the larger between viewport width and height

Which Units to Use and When

  • Use px when you need fixed size (icons, borders)
  • Use em or rem for font-size and spacing for scalable design
  • Use % for layout that depends on parent size
  • Use vw and vh for full-screen sections or responsive designs

Summary

  • px: fixed size
  • em: relative to parent font-size
  • rem: relative to root font-size
  • %: relative to parent element size
  • vw: relative to viewport width
  • vh: relative to viewport height
Scroll to Top