Your Own Class with @apply

Tailwind can put a whole list of its classes under one name of your choice. In style.css, you write a rule for your own class, as in the CSS course, and in it, @apply followed by Tailwind's classes:

@layer components {
	.btn {
		@apply inline-block rounded-full bg-brand-500 px-5 py-2 font-semibold text-white transition-colors hover:bg-brand-600;
	}
}

@apply takes the CSS of the listed classes and puts it into your rule: .btn gets display: inline-block, the rounded corners, the background, the padding and everything else. Variants work too: from hover:bg-brand-600, Tailwind makes a rule for .btn:hover. The name btn (short for button) is our choice, but you'll see it on many websites.

Then one class in the HTML is enough:

<a href="#" class="btn mt-4">Adopt Tiger</a>

We've left mt-4 out of .btn: the space above a button depends on where the button is, not on what a button looks like. You can combine your class with any utility classes.

Why @layer components? Tailwind sorts its CSS into layers (in CSS, they're called cascade layers): first base (Preflight), then components, and last utilities, the utility classes. When rules in different layers set the same property, the rule in the later layer wins, whatever its specificity or its place in the stylesheet. We've put .btn into the components layer, so utility classes always win over it. That's why the hero's button can be a btn and still be bigger:

<a href="#cats" class="btn mt-8 px-8 py-3 text-lg">Meet our cats</a>

px-8 and py-3 win over px-5 and py-2 from .btn. Without @layer components, the rule for .btn wouldn't be in any layer, and CSS outside layers wins over all layers: px-8 would do nothing.

Mistakes in @apply. As you know, a misspelled class in the HTML simply does nothing. In @apply, it's different: Tailwind can't make your rule, so the page gets none of the CSS from style.css, and an error appears in red under the preview, for example:

style.css: Cannot apply unknown utility class `bg-brnd-500`

It tells you which class Tailwind doesn't know. Fix it and run the code again.

Instructions

In style.css, after the @theme block, add the @layer components block with the class .btn from the first example above.

In each of the four cats' cards, replace all the classes of the Adopt button with btn mt-4. The buttons should look just as they did before.

Replace the classes of the Meet our cats button in the hero with btn mt-8 px-8 py-3 text-lg. Then try a mistake: in @apply, change bg-brand-500 to bg-brnd-500, click Run and read the error under the preview. Then fix it.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/7