While we strongly believe you can get a lot further with just utilities than you might initially expect, we don’t believe that a dogmatic utility-only approach is the best way to write CSS.

    For example, using a utility-first approach, implementing a button style early in a project might look something like this:

    If this is the only button in your project, creating a custom component class for it would be premature abstraction; you’d be writing new CSS for no measurable benefit.

    If on the other hand you were reusing this button style in several places, keeping that long list of utility classes in sync across every button instance could become a real maintenance burden.

    When you start to notice repeating patterns of utilities in your markup, it might be worth extracting a component class.

    To make this as easy as possible, Tailwind provides the directive for applying the styles of existing utilities to new component classes.

    Extracting Components - 图2

    Note that hover:, , and {screen}: utility variants can’t be mixed in directly. Instead, apply the plain version of the utility you need to the appropriate pseudo-selector or in a new media query.

    Say you have these two buttons:

    It might be tempting to implement component classes for these buttons like this:

    The issue with this approach is that you still have potentially painful duplication.

    If you wanted to change the padding, font weight, or border radius of all the buttons on your site, you’d need to update every button class.

    Now you’d apply two classes any time you needed to style a button:

    Extracting Components - 图4

    This makes it easy to change the shared styles in one place by just editing the class.

    It also allows you to add new one-off button styles without being forced to create a new component class or duplicated the shared styles:

    Since Tailwind’s utility classes don’t rely on !important to defeat other styles, it’s important that you add your component classes before any utility classes in your CSS.

    Here’s an example: