CSS Units

ADVERTISEMENT

CSS units define the measurement used for properties like width, height, padding, font-size, margin, etc.

There are two main types:

1. Absolute Units (Fixed Size)

These don’t change based on screen or user settings.

UnitDescriptionExample
pxPixels (most common)font-size: 16px;
ptPoints (print)12pt
cm, mm, inPhysical lengths (rarely used in web)2cm, 1in

Use px when you want a fixed size across all devices.

2. Relative Units (Flexible, Responsive)

These adapt to screen size, font size, and other factors.

UnitRelative ToExample
%Parent element sizewidth: 80%;
emFont size of current elementpadding: 2em;
remFont size of root <html>font-size: 1.5rem;
vw1% of viewport widthwidth: 50vw;
vh1% of viewport heightheight: 100vh;

🔁 em vs rem

  • 1em = 100% of the current element’s font size.
  • 1rem = 100% of the root (html) font size (more consistent).

Example:

html {
  font-size: 16px;
}
p {
  font-size: 1.5rem; /* 24px */
}

📐 Example with Units

.container {
  width: 80%;       /* responsive */
  max-width: 1200px; /* limit */
  padding: 2rem;
  font-size: 1.2em;
  height: 100vh;
}

🧠 Best Practices

  • Use %, vw, and vh for layouts and responsiveness.
  • Use rem for scalable and consistent typography.
  • Avoid pt, cm, in unless for print styles.

ADVERTISEMENT