Sub topic 1
The utility-first approach
Utility-first styling means you build an interface by combining small classes that each do one thing, directly in your markup. This chapter explains the working model, compares it with writing custom CSS classes, and covers the errors that trip people up early. Later chapters cover each utility family in detail.
Prerequisites
This chapter assumes you already know:
- Basic HTML structure and common elements such as
div,h2,p,button,nav,ul, anda. - Core CSS ideas: the box model, selectors, and specificity.
- How to run commands in a terminal and use a package manager such as npm. Setup is covered in the next chapter, so you do not need Tailwind installed to follow this one.
Knowing what a component is in a front-end framework helps, but it is not required.
The working model
A utility class is a class name that maps to one CSS declaration, or to a very small group of related declarations. For example:
| Class | CSS it produces |
|---|---|
| `p-6` | `padding: 1.5rem` |
| `bg-white` | `background-color: white` |
| `text-xl` | `font-size` and `line-height` for the "xl" step |
| `rounded-xl` | `border-radius` for the "xl" step |
| `font-semibold` | `font-weight: 600` |
You style an element by listing the utilities it needs in its class attribute. You do not invent a name for the element and then write a rule for that name in a separate stylesheet.
Here is a card built only from utilities:
<div class="max-w-sm rounded-xl bg-white p-6 shadow-md">
<h2 class="text-xl font-semibold text-slate-900">Card title</h2>
<p class="mt-2 text-slate-600">Some supporting text for the card.</p>
<button class="mt-4 rounded-lg bg-indigo-600 px-4 py-2 text-white hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500">
Read more
</button>
</div>Read the outer div from left to right:
max-w-smcaps the width at a small preset.rounded-xlrounds the corners.bg-whitesets the background color.p-6adds padding on all sides.shadow-mdadds a medium drop shadow.
The button shows that state is also expressed as a class. hover:bg-indigo-700 applies only while the pointer is over the button, and focus:ring-2 draws a ring only when the button has focus. A prefix followed by a colon is called a variant. Variants are covered in their own chapters, but you can already see that they do not need a separate selector or a separate file.
Comparing it with custom CSS classes
The traditional approach names a component and styles the name. The same card would look like this:
<div class="card">
<h2 class="card-title">Card title</h2>
<p class="card-text">Some supporting text for the card.</p>
<button class="card-button">Read more</button>
</div>.card {
max-width: 24rem;
border-radius: 0.75rem;
background: white;
padding: 1.5rem;
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
}
.card-title {
font-size: 1.25rem;
font-weight: 600;
color: #0f172a;
}
.card-text {
margin-top: 0.5rem;
color: #475569;
}
.card-button {
margin-top: 1rem;
border-radius: 0.5rem;
background: #4f46e5;
padding: 0.5rem 1rem;
color: white;
}
.card-button:hover {
background: #4338ca;
}Both versions produce the same result. The trade-offs differ:
| Concern | Custom classes | Utility-first |
|---|---|---|
| Naming | You must name every element, and names drift (`card-body`, `card-content`, `card-inner`). | No names for one-off elements. |
| Where styles live | Markup in one file, rules in another. You switch files to understand or change an element. | The markup shows the styling. |
| Side effects of edits | Changing `.card` can affect every place that uses it, including places you forgot. | Editing classes on one element affects only that element. |
| CSS growth | The stylesheet grows with every new component, and old rules are hard to delete safely. | The generated CSS grows only with the number of distinct utilities, which levels off. |
| Specificity | Overrides require careful selector ordering. | Each utility has the same low specificity, so conflicts are rare and predictable. |
| Values | Each author picks their own padding and colors, such as `13px` here and `14px` there. | Values come from a shared scale, which keeps spacing and color consistent. |
| Readability of markup | Short and clean class lists. | Long class lists. |
The last row is the real cost of the approach. The sections on reuse below explain how to manage it.
Why the shared scale matters
Utility names like p-4, text-slate-600, and rounded-lg do not take free-form values. Each one points to a step in a design scale, which is a fixed set of allowed spacing, size, and color values. When every developer picks from the same scale, a design stays visually consistent without a style guide that people must remember. The scale is also configurable, which a later chapter covers.
How the pieces fit together
Tailwind is a build step plus a vocabulary of class names. You write class names in your files. Tailwind scans those files for class names it recognizes and writes a CSS file containing only the rules that match. The browser then loads that one stylesheet.
This has a practical consequence that you should keep in mind from the start. Tailwind finds classes by reading your source as plain text. It does not run your code. The next chapter covers the build in detail, and a later chapter covers the errors this causes with dynamic class names.
Composing utilities for layout
Utilities are not limited to decoration. Layout is built the same way. This navigation bar uses flexbox utilities:
<nav class="flex items-center justify-between p-4">
<a href="/" class="text-lg font-bold">Brand</a>
<ul class="flex gap-4">
<li><a href="/docs">Docs</a></li>
<li><a href="/blog">Blog</a></li>
</ul>
</nav>flexturns thenavinto a flex container, so its children sit on one row.items-centeraligns the children vertically on the cross axis.justify-betweenpushes the logo to one end and the list to the other.gap-4adds space between the links without margins on individual items.
Each utility does one job, and you combine them to get the layout you want. If you later want the links centered instead, you change justify-between to justify-center. You do not edit a stylesheet.
Responsive and state styling in the same place
Because variants are prefixes, the same markup can describe how an element changes with screen size. The prefixes are mobile-first: an unprefixed utility applies at all sizes, and a prefixed utility applies from that breakpoint upward.
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div class="rounded bg-slate-100 p-4">One</div>
<div class="rounded bg-slate-100 p-4">Two</div>
<div class="rounded bg-slate-100 p-4">Three</div>
</div>This grid has one column by default, two columns from the sm breakpoint, and three from lg. In the custom CSS approach, you would write a media query in a stylesheet for the same effect. Here the behavior sits next to the element it affects.
Dark mode follows the same pattern:
<div class="bg-white text-slate-900 dark:bg-slate-900 dark:text-white">
Adapts to the dark color scheme.
</div>The dark: prefix applies its utilities only when dark mode is active.
Managing long class lists
Long class lists are the most common objection, and it is a fair one. Three habits keep them manageable.
- Extract components, not CSS classes. If a card appears in ten places, create one component in your framework (a React component, a Vue component, a template partial) and use it ten times. The class list then lives in one place, and you edit it once. This is the recommended first choice.
- Use loops for repeated items inside one file. If you render a list of cards from data, the class list appears once in the loop body.
- Use
@applyas a fallback. When you cannot use a component, for example in plain HTML that is rendered by a system you do not control, you can inline utilities into a custom class:
.btn-primary {
@apply rounded-lg bg-indigo-600 px-4 py-2 text-white hover:bg-indigo-700;
}A later chapter compares these options in detail. For now, remember that utility-first does not mean copying the same twenty classes into every file.
Common errors
Treating utilities as inline styles
Utilities look like inline styles, but they are not the same. Inline style attributes cannot express hover or focus states, media queries, or dark mode, and they cannot use a shared scale. Utilities can do all of these because they compile to real CSS rules with selectors and media queries.
Building class names from fragments
Tailwind reads your source as text and looks for complete class names. If you assemble a class name from pieces, the full name never appears in the source, so no CSS is generated for it.
// Does not work: Tailwind cannot see the full class name in the source.
const bad = (color) => `text-${color}-600`;
// Works: every complete class name appears literally in the source.
const colorClasses = {
red: 'text-red-600',
green: 'text-green-600',
};
const good = (color) => colorClasses[color];The symptom is that the class is present in the rendered HTML, but the element has no style. A later chapter explains detection fully. The rule to remember now is to write class names in full.
Conflicting utilities on one element
If you put two utilities that set the same property on one element, such as p-4 p-6, the winner is decided by the order of the rules in the generated stylesheet, not by the order of the class names in your class attribute. Do not rely on one overriding the other. Instead, make the choice in your code, for example by passing a single value to a component, and emit only one of the two classes.
Reaching for custom CSS too early
If you find yourself writing a stylesheet rule for something that a utility already covers, check the documentation first. Custom CSS is still available and sometimes right, but starting with utilities keeps your stylesheet small.
Skipping the design scale
Writing a one-off value for every element defeats the consistency benefit. Tailwind allows one-off values in square brackets, for example:
<div class="w-[320px] bg-[#1da1f2] p-[13px]">
One-off values written directly in square brackets.
</div>Use this sparingly. If the same value appears more than a couple of times, add it to the theme as a design token instead. In Tailwind v4, a CSS variable in the --color-* namespace inside @theme creates matching utilities:
@import "tailwindcss";
@theme {
--color-brand: #4f46e5;
}This gives you bg-brand, text-brand, and the other color utilities with no extra work.
When utility-first is a good fit, and when it is not
Utility-first works best when:
- You build interfaces from components in a framework, so class lists live in one place.
- You want consistent spacing, type, and color without maintaining a large stylesheet.
- Several people edit the UI and need to avoid breaking each other's styles.
It is a weaker fit when:
- You must style markup you cannot edit, such as HTML produced by a content system. Targeting that markup with selectors in a stylesheet is more practical.
- Your team has no component or template mechanism and would repeat large class lists in many files.
- You need styles that depend on complex selectors between elements. You can use custom CSS alongside Tailwind for these cases.
You can mix both approaches in one project. Utilities handle most of the work, and a small amount of hand-written CSS covers the exceptions.
Summary
- A utility class maps to one CSS declaration and is applied in markup.
- Compared with custom classes, utilities remove naming, avoid side effects from edits, and keep values on a shared scale. The cost is long class lists.
- Variants such as
hover:,sm:, anddark:put state, responsive, and theme behavior next to the element. - Tailwind scans source text, so write complete class names.
- Manage repetition with components first, loops second, and
@applylast.
Exercise
A teammate writes const cls = (size) => text-${size}; and calls it with "lg" and "xl". The rendered HTML contains class="text-lg", but the text is not larger. What is the cause, and how do you fix it?
Show answer
Tailwind scans source files as plain text and looks for complete class names. The strings text-lg and text-xl never appear in full in the source, because they are assembled at run time, so no CSS rules are generated for them. Fix it by writing the full names in the source, for example with a lookup object such as { lg: 'text-lg', xl: 'text-xl' } and returning sizes[size].
Exercise
A page shows the same card markup, with about fifteen utility classes, in twelve places. Which approach do you try first to avoid repeating the class list, and when would you use @apply instead?
Show answer
Extract a component in your framework (or a template partial) so the class list exists in one place and is edited once. Use @apply only when a component is not practical, such as plain HTML rendered by a system you cannot change, where you need a named class that bundles utilities.
Exercise
Why is p-4 p-6 on one element a bad way to let a caller override padding?
Show answer
Both utilities set the same property, and which one wins depends on the order of the rules in the generated stylesheet, not on the order in the class attribute. The result is not something you should rely on. Choose one value in code and emit only one of the two classes.