Your Own Utility

A class made with @apply has one limit: it isn't a utility class, so it doesn't work with variants. hover:btn or md:btn does nothing, because variants work only with the utility classes that Tailwind knows. And sometimes you need CSS that no class of Tailwind makes, such as a pattern in the background.

For that, there's @utility. It makes a new utility class that works just like Tailwind's own: on its own, with any variant, and in @apply too. After @utility, you write the name of the class (without a dot) and then the declarations, as in a rule:

@utility bg-stripes {
	background-image: repeating-linear-gradient(45deg, transparent 0 12px, rgba(255, 255, 255, 0.5) 12px 24px);
}

The background-image property paints a picture in the background of an element, on top of its background color. Here, the picture isn't a file: repeating-linear-gradient() makes the browser paint stripes, slanted at 45 degrees (45deg). They take turns every 12 pixels: a transparent one, through which the background color shows, and a white one at half opacity. On our light orange background, they look like this:

Now bg-stripes is a class like any other: you can write md:bg-stripes, hover:bg-stripes and so on. It's in the utilities layer, so it wins over classes like .btn. And Tailwind makes its CSS only when a page uses it, as with its own classes. Name your utilities the way Tailwind does: by what they change and how (bg- for the background).

Instructions

At the end of style.css, add the utility bg-stripes from the example above.

On a phone, the hero is narrow and full of text, and stripes would make it look busy. On a wider screen, they fill the space nicely. Add the class md:bg-stripes to the hero (the first section), then switch the preview to 768 px or 1280 px to see the stripes.

Start programming for free

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

Or sign up with:

5/7