Search code examples
csshyperlinktailwind-cssapplylayer

How can i use Tailwind directive @layer @apply, when i was in Tailwind CDN environment?


According to the tailwind official doc: https://tailwindcss.com/docs/installation/play-cdn

I can use @layer @apply in html file, i just need to import CDN, then write the <style> with type="text/tailwindcss"

  <script src="https://cdn.tailwindcss.com"></script>
  <style type="text/tailwindcss">
    @layer components {
      .btn_style {
        @apply outline outline-sky-400 p-1 bg-sky-200 rounded-md font-bold;
      }
    }
  </style>

it worked, i can reuse class .btn_style, as my own components.

But, i want multiple html files can load this <style type="text/tailwindcss">

I tried to made the area: <style type="text/tailwindcss"></style> as an independent CSS file (style.css) . And when i use <link> to import style.css, it failed, how can i do?

  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="stylesheet" href="style.css" type="text/tailwindcss">

Solution

  • How about creating a script? - Let's call it "mystyles.js"

    This contains:

        document.head.appendChild(
          Object.assign(document.createElement('style'), {
            type:'text/tailwindcss',
            textContent: `
              @layer components {
                .btn_style {
                  @apply outline outline-sky-400 p-1 bg-sky-200 rounded-md font-bold;
                }
              }`
          })
        ); 
    

    and include in each HTML file with <script src="mystyles.js"></script>

    Then you can put whatever tailwind styles you want in the textContent: section of the script.