Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

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

  2. 2

    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.

Back

5/7

  1. 1. Your Own Colors
  2. 2. Your Own Font
  3. 3. Repeating Classes
  4. 4. Your Own Class with @apply
  5. 5. Your Own Utility
  6. 6. Which Way to Choose
  7. 7. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.