Sub topic 3
Hover, Focus, and Responsive Variants in `@apply`
Assume basic CSS, Tailwind utilities, and a component framework. In @apply, write state and responsive rules as normal CSS selectors or media queries.
Applying variants
@layer components {
.btn {
@apply rounded-md px-4 py-2 font-semibold text-white;
@apply bg-blue-600;
}
.btn:hover {
@apply bg-blue-700;
}
.btn:focus-visible {
@apply outline-none ring-2 ring-blue-500 ring-offset-2;
}
@media (min-width: 768px) {
.btn {
@apply px-6;
}
}
}This keeps the variant behavior in CSS while reusing Tailwind’s utility definitions.
Scoped and modular styles
Tailwind CSS v4 requires a stylesheet that uses @apply to reference the file containing the Tailwind theme and utilities. This matters in Vue, Svelte, and some CSS module setups.
<style scoped>
@reference "../../app.css";
.button {
@apply rounded-md bg-blue-600 px-4 py-2 text-white;
}
.button:hover {
@apply bg-blue-700;
}
</style>The path is relative to the stylesheet. In Svelte, use the same @reference statement inside the component’s <style> block. CSS modules usually need the same reference, depending on the build integration. A scoped style still receives framework-specific scoping, so inspect the generated CSS if a selector does not match.
Defining custom utilities
Tailwind v4 provides @utility for utilities that should work with variants:
@import "tailwindcss";
@utility accent-ring {
box-shadow: 0 0 0 3px rgb(59 130 246 / 35%);
}You can then write hover:accent-ring or md:accent-ring in markup.
Pitfalls and limits
@applydoes not replace repeated markup or behavior.- Dynamic class names such as `
bg-${color}-500` may not be detected. Use complete class names in source code. - Circular use of component classes or custom utilities can fail during compilation.
- A shared class can hide important differences in accessibility or layout.
- Source order and CSS specificity still affect the result.
| Reuse case | Usually choose |
|---|---|
| Repeated records in a template | Loop |
| A control with behavior and variants | Component |
| A small, stable CSS declaration group | `@apply` |
Exercise
Exercise
Which strategy fits three buttons with identical structure but different labels and click behavior?
Show answer
Extract a button component, pass the label and behavior as props, and use a variant prop for intentional visual differences.