Search code examples
csstailwind-csscodepen

How to use tailwindcss's @apply and others in codepen


Is it possible, and if so how, to use things like @apply and extend tailwind components in a codepen ? For example doing something like:

.button {
    @apply rounded-4 border-2 border-blue-500;
}

I tried to write my css using @apply with some css pre-processors in the pen's settings.


Solution

  • I don't believe CodePen has any native support for Tailwind CSS, so I'd assume you're using the CDN.

    Thus, to use @apply with the CDN version, as per the documentation:

    3. Try adding some custom CSS

    Use type="text/tailwindcss" to add custom CSS that supports all of Tailwind's CSS features.

    <style type="text/tailwindcss">
      @layer utilities {
        .content-auto {
          content-visibility: auto;
        }
      }
    </style>
    

    In the same way, you'd do:

    tailwind.config = {
      theme: {
        extend: {
          borderRadius: {
            '4': '4px',
          },
        },
      },
    };
    <script src="https://cdn.tailwindcss.com/3.4.3"></script>
    
    <style type="text/tailwindcss">
    .button {
      @apply rounded-4 border-2 border-blue-500;
    }
    </style>
    
    <div class="button">Foo</div>


    As an aside, you may also wish to avoid @apply altogether as recommended by Adam Wathan, creator of Tailwind:

    • https://twitter.com/adamwathan/status/1226511611592085504

      Confession: The apply feature in Tailwind basically only exists to trick people who are put off by long lists of classes into trying the framework.

      You should almost never use it 😬

      Reuse your utility-littered HTML instead.

    • https://twitter.com/adamwathan/status/1559250403547652097

      I can say with absolute certainty that if I started Tailwind CSS over from scratch, there would be no @​apply 😬

      The behavior is outrageously complicated, everyone struggles to build the right mental model of what it's supposed to do, and it encourages bad CSS architecture.