Lesson 3 / 25

How Classes Become CSS

Tokens as CSS variables.

By · 15 years in web development

Only what you use, built on variables

Tailwind generates CSS only for class names it finds in your files. In v4 each utility refers to a theme variable: bg-blue-500 sets background-color: var(--color-blue-500) and p-4 sets padding: calc(var(--spacing) * 4), where --spacing defaults to 0.25rem, so p-4 is 1rem. Variants wrap rules: hover: adds a :hover selector and md: adds a media query. Because class names are detected as plain text, never build class names dynamically from string fragments.

Generated CSS for a few classes

Simplified from Tailwind v4 output for p-4, bg-blue-500, hover:bg-blue-600 and md:flex.

.p-4 { padding: calc(var(--spacing) * 4); }
.bg-blue-500 { background-color: var(--color-blue-500); }
.hover\:bg-blue-600:hover { background-color: var(--color-blue-600); }   /* inside @media (hover: hover) */
@media (width >= 48rem) {
  .md\:flex { display: flex; }
}

Dynamic class names are not detected

Write complete class names so the scanner can find them.

// Wrong: "bg-red-500" never appears as a whole word in the source
const cls = `bg-${color}-500`;

// Right: map to complete class names
const colors = { danger: "bg-red-500", success: "bg-green-500" };
const cls2 = colors[variant];

Quick check: Why does `bg-${color}-500` fail to produce styles?

  • It needs !important
  • Template literals are not allowed in HTML
  • Red is not a Tailwind colour
  • Tailwind detects complete class names as text, and that string never appears whole
Answer

Tailwind detects complete class names as text, and that string never appears whole — Use full class names.