Sub topic 10
Utility classes and when to use them
What this chapter assumes
You should know CSS selectors, specificity and source order, and you should have read the earlier chapters on BEM, design tokens and @layer. This chapter builds on all three. You don't need any utility framework experience.
What a utility class is
A utility class does one job and does not depend on context. .p-0 sets padding to zero. .text-center centers text. .hidden hides an element. A utility class has no name tied to a component, and it usually has a single declaration.
Compare two ways to remove padding from a card:
- A component approach adds a modifier such as
.card--flushand writes its rule in the card's stylesheet. - A utility approach adds
.p-0to the element in the markup.
<article class="card p-0">
<h2 class="card__title">Release notes</h2>
</article>The utility moves a decision from the stylesheet to the markup. That move is the source of both its benefits and its costs.
Why utilities help at scale
Utilities address several of the scaling problems from the first chapters.
- Flat specificity. Every utility is one class selector, so specificity is
0,1,0. You never need a longer selector to win. - Bounded growth. Component CSS grows with each new variation. A utility set grows only when you add a new property or value, and it stops growing once your design scale is covered.
- Safe changes. Adding
.mt-4to one element cannot break another component. Editing.cardcan. - Less naming work. One-off spacing and alignment do not need a name like
.card--with-extra-gap.
Utilities work best for small adjustments that depend on where an element sits, such as spacing between siblings, alignment, visibility and text alignment. They fit poorly when the same group of utilities is copied across many templates, because the group is then really a component.
Costs and failure modes
- Repeated markup. A button may need eight utilities. Copy that into forty templates and a design change means forty edits.
- Weak semantics in the stylesheet. Reading
class="flex gap-4 p-2"tells you how something looks. It does not tell you what the element is. - Inconsistent values. If utilities accept arbitrary values, the design scale erodes. This is why a utility set should be built from design tokens.
- Override fights. A utility must beat the component rule it modifies. Without a plan for that, developers reach for
!important. - Class name bloat. Long class lists make markup harder to scan and review.
Build utilities from tokens
Define the scale once as custom properties, then let utilities read it. This keeps utilities and components in agreement.
:root {
--space-0: 0;
--space-2: 0.5rem;
--space-4: 1rem;
--space-8: 2rem;
}Then generate or write utilities that consume those tokens:
.mt-2 { margin-top: var(--space-2); }
.mt-4 { margin-top: var(--space-4); }
.mt-8 { margin-top: var(--space-8); }If the spacing scale changes, you edit the tokens, and both components and utilities follow. Only publish values the design system actually allows. A small set such as four to eight spacing steps is easier to review than an open-ended one.
Make utilities win with `@layer`
A utility is only useful if it reliably overrides the component it is applied to. Do that with layer order, not with !important.
@layer reset, base, components, utilities;
@layer components {
.card {
padding: 1rem;
margin-top: 2rem;
}
}
@layer utilities {
.p-0 { padding: 0; }
.mt-4 { margin-top: 1rem; }
}An element with class="card p-0 mt-4" gets no padding and a 1rem top margin. Later layers beat earlier ones regardless of specificity, so utilities win even if a component selector is more specific, such as .sidebar .card.
Combine utilities with BEM components
A good division of work keeps each tool in its role:
- BEM components own what something is: structure, typography, color, states.
- Utilities own where it sits and small one-off adjustments: margin, alignment, visibility.
<section class="card card--featured mt-8">
<h2 class="card__title">Release notes</h2>
<p class="card__body">What changed this week.</p>
<a class="button text-center" href="/notes">Read more</a>
</section>Here .card does not set its own outer margin. The page decides the spacing with mt-8. This follows a common BEM rule: a block should not position itself relative to its neighbors, because it can't know where it will be used.
Avoid using utilities to restyle the inside of a component. If every .button in the project is given bg-accent text-white rounded, the button is missing a modifier or a base style. Move the repeated group into the component.
Responsive and state variants
Utilities often need to change at breakpoints. A common convention puts the breakpoint in the class name. The colon must be escaped in CSS.
@layer utilities {
.hidden { display: none; }
@media (min-width: 48rem) {
.md\:hidden { display: none; }
.md\:block { display: block; }
}
}<nav class="hidden md:block">...</nav>Three details matter here:
- Variants must come after the base utility in source order, because they have the same specificity. Putting the media query block after the base rules is enough.
- Every variant you add multiplies the stylesheet size. Offer variants only for properties that need them.
- Prefer
remin media queries so that breakpoints respect the user's font size setting.
Add a few accessibility utilities as well. The visually hidden pattern is one of the few places where a utility with several declarations is normal:
@layer utilities {
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
}
}Gotchas
- Dynamic class names break tools. Build tools that remove unused CSS scan your files for complete class strings. Code such as
"mt-" + sizenever containsmt-4as text, so the rule may be dropped. Write full names, or map values to complete strings in a lookup object. - Utilities and
!important. Some projects mark every utility!important. Inside a layered setup this is unnecessary and creates a trap: with!important, layer order reverses, so earlier layers win. Leave it out. - Utility versus state.
.p-0will beat.card:hover { padding: 1rem }when both are in the cascade and utilities are the later layer. Decide whether that is what you want, and keep state styles out of properties you also expose as utilities. - Linting. The Stylelint rule
declaration-no-importantfrom the earlier chapter keeps!importantout of both components and utilities. Add a convention that utilities live in one file so rules likeselector-max-specificitystay simple.
Choosing: a decision guide
| Situation | Better choice |
|---|---|
| One-off margin, gap or alignment depending on page context | Utility |
| Same set of five or more declarations repeated in many places | Component class or modifier |
| A value that must follow the design scale | Utility generated from tokens |
| A style that depends on a state like `:hover` or `[aria-expanded]` | Component rule |
| Hiding content visually or from layout | Utility |
| Content that comes from a CMS where editors cannot add classes | Component or element styles |
A useful test: if you would be embarrassed to explain why the component does not own this style, it should be a component style. If the style describes the component's surroundings, it should be a utility.
Summary of working rules
- Build utilities from tokens and publish only scale values.
- Put utilities in the last layer and declare the layer order first.
- Let components own identity and utilities own placement.
- Promote repeated utility groups into components.
- Write complete class names so tooling can find them.
Exercise
A teammate adds .p-0 { padding: 0; } in a utilities layer, but <div class="card p-0"> still has padding. The .card rule is in @layer components, and @layer components, utilities; is declared first. Name two likely causes and how to check each.
Show answer
First, another .card padding rule may exist outside any layer, for example in a legacy stylesheet. Unlayered styles beat all layered styles. Check DevTools for the winning rule and whether it shows a layer name. Second, the layer order may not be what you think, because a layer name that appeared earlier in another file fixes its position. Check the order in which @layer names first appear across loaded stylesheets. A third possibility is that .card uses !important, which reverses layer priority. Fix by layering the legacy CSS, declaring the order first, or removing !important.
Exercise
A button uses class="px-4 py-2 bg-accent text-white rounded border-2" in 30 templates. Is this a good use of utilities? What would you do, and which part of the markup would you keep as utilities?
Show answer
No. The same group is repeated, so it is really a component. Create a .button block with the padding, background, text color, radius and border built from tokens, and add modifiers such as .button--secondary for variations. Keep utilities for context-dependent adjustments on specific instances, such as mt-4 or text-center.