Reusing TailwindCSS styles

Alex - Aug 26 - - Dev Community

TailwindCSS got very popular, but one big disadvantage - bunch of inline classes clutter the code.
Can use Tailwind Fold extension
to improve readability, but need more to make styles reusable.

Have a styled code

    <div
      className="codeblock shadow-md hover:shadow-2xl bg-white border border-gray-200 rounded-lg dark:border-gray-700 h-full"
      data-nosnippet="true"
    >
      <div className="flex h-12 justify-between dark:bg-gray-900 font-mono border-b border-zinc-700 text-sm select-none">
        <div className="flex border-zinc-800 gap-2 items-center p-2 pl-4 h-auto">
          <div className="h-4 w-4 rounded-full bg-zinc-700"></div>
          <div className="h-4 w-4 rounded-full bg-zinc-700"></div>
          <div className="h-4 w-4 rounded-full bg-zinc-700"></div>
        </div>

        <div className="flex items-center border-zinc-700 border-l-2 h-full relative px-4 ">
          {name}
        </div>
      </div>

      <code>
        <pre
          dangerouslySetInnerHTML={{ __html: text }}
          className=" dark:bg-gray-900 text-sm font-mono p-5"
        ></pre>
      </code>
    </div>
Enter fullscreen mode Exit fullscreen mode

Approach is to use @apply directive in css file to apply any classes.

In css file, e.g. global.css

@layer components {
  .code-title {
    @apply text-black text-center text-xl mt-2;
  }

  .code-file {
    @apply shadow-md hover:shadow-2xl bg-white border border-gray-200 rounded-lg dark:border-gray-700 h-full;

    .header {
      @apply flex h-12 justify-between dark:bg-gray-900 font-mono border-b border-zinc-700 text-sm select-none;

      .dots {
        @apply flex border-zinc-800 gap-2 items-center p-2 pl-4 h-auto;

        .dot {
          @apply h-4 w-4 rounded-full bg-zinc-700;
        }
      }

      .filename {
        @apply flex items-center border-zinc-700 border-l-2 h-full px-4;
      }
    }

    .code {
      @apply dark:bg-gray-900 text-sm font-mono p-5;
    }

    .shiki {
Enter fullscreen mode Exit fullscreen mode

This way can apply styles by a className.
Also, notice that can use nested rules in plain CSS, CSS nesting is widely supported.

Tailwind will compile those styles internally
Compiled styles

Look at before and after diff.
diff

Gotcha - @apply rule isn't a standard way, it's works with PostCSS (used internally in Tailwind). Had to install PostCSS extension for VSCode to recognize this syntax.

Official documentation about it.

. . . . . . . . . . . . .