Lesson 16 +10 XP

Managing Duplication & Conflicts

Managing Duplication & Conflicts

Building projects with utility classes can lead to repeated class lists - and occasionally, conflicting classes.

Handling repetition

  1. Loops - elements rendered in a loop only have their classes written once.
  2. Multi-cursor editing - for duplication in a single file, select and edit all class lists at once.
  3. Components - in React/Svelte/Vue, extract a component. In templating languages, use a partial.
  4. Custom CSS - for a simple element where a partial is overkill, a class like .btn-primary with @apply is fine.

Conflicting utility classes

When two classes target the same property, the one that appears later in the stylesheet wins. In general, just don't add two conflicting classes:

<div className={gridLayout ? "grid" : "flex"}>...</div>

The important modifier

Force a class with ! at the end:

<div class="bg-teal-500 bg-red-500!">...</div>

The important flag

Mark all utilities as !important when integrating into a project with high-specificity CSS:

@import "tailwindcss" important;

The prefix option

Avoid conflicts with your own class names by prefixing everything:

@import "tailwindcss" prefix(tw);

This generates tw:text-red-500 instead of text-red-500.

TL;DR

  • Use loops, components, and partials to avoid duplication.
  • Don't add conflicting classes - pick one.
  • ! marks a single class important.
  • important / prefix(tw) options help integrate with existing CSS.