CSS Units

CSS uses absolute and relative units to size text, spacing, and layouts. Prefer relative units (like rem, %, vw) for responsive and accessible designs. Combine with functions like calc() and clamp() for precise, fluid control.

1) px vs em vs rem


/* Root font-size drives rem: */
:root { font-size: 16px; }

/* em: relative to the element’s parent font-size */
.parent { font-size: 20px; }
.child-em { font-size: 1.2em; } /* 24px */

/* rem: relative to the root (html) font-size */
.child-rem { font-size: 1.2rem; } /* 19.2px if root=16px */

px (fixed)

160px wide

em (relative to parent)

Parent 20px
Child 1.2em (≈24px)

rem (relative to root)

Child 1.2rem (root-based)

Tip: Use rem for type scale & spacing to respect user zoom; use em for component-relative sizing.

2) % (Percentage)


/* Width/height relative to the parent box */
.child { width: 50%; }
50% of parent

3) Viewport Units: vw, vh, vmin, vmax


.hero { height: 60vh; }     /* 60% of viewport height */
.panel { width: 40vw; }   /* 40% of viewport width */

40vw × 15vh

20vmin square

vmax example

Use for full-viewport sections, hero banners, and fluid spacing tied to screen size.

4) Typographic Units: ch & ex


.content { max-width: 60ch; } /* ~60 characters per line */
60ch measure

Good line length (45–75ch) improves readability by balancing eye movement and word shape recognition.

ex unit

ex approximates the x-height of the font; it’s less common but can help with fine typographic alignment.

5) calc() for Dynamic Math


.content-bar{
  width: calc(100% - 160px - 12px); /* container - sidebar - gap */
}
Width via calc( )

6) Fluid Typography with clamp()


h1 {
  font-size: clamp(1.25rem, 2vw + 1rem, 2.5rem);
}

Fluid heading scales with viewport

Minimum 1.25rem, grows with 2vw + 1rem, capped at 2.5rem.

7) Absolute Units (cm, mm, in, pt, pc)


/* Typically for print stylesheets */
@media print {
  .ticket { width: 8cm; height: 3cm; }
}

Absolute units are device-independent lengths. On screens, prefer relative units for responsiveness.

Best Practices:

  • Use rem for type scale and consistent spacing; adjust :root for global sizing.
  • Use em when a component should scale relative to its own context (e.g., padding with text size).
  • Use viewport units (vw/vh) for sections that must fill the screen.
  • Keep line length around 60ch for readable paragraphs.
  • Combine units with calc() and clamp() for robust, fluid layouts.