Need help using @apply directive in Tailwind CSS

Viewed 838

I found the @apply directive an easy way to reuse code but when I'm using the @apply directive in tailwind css it is showing me error You cannot @apply the btn utility here because it creates a circular dependency.

This is my HTML code

            <a class="bg-transparent border btn border-black hover:bg-black hover:text-white px-6 py-2 rounded-2xl"
                href="">Browse</a>
            <a>Look</a>
        

I want the classes of the 1st a tag in my second tag by just using @apply directive

And this is my tailwind css file where I put the @apply directive

@tailwind base;
@tailwind components;

.btn{
@apply bg-transparent border btn border-black hover:bg-black hover:text-white px-6 py-2 rounded-2xl;
}
@tailwind utilities;
1 Answers

This error keeps showing because you added the btn class inside itself in your CSS file

your HTML should be like this:

<a class="btn" href="">Browse</a>

<a>Look</a>

and your CSS should be like this:

@tailwind base;
@tailwind components;
.btn{
@apply bg-transparent border  border-black hover:bg-black hover:text-white px-6 py-2 rounded-2xl;
}
@tailwind utilities;

also, it's a better practice to add your components with @layer components so you can add new components classes wherever you want and not only between @tailwind components; and @tailwind utilities;

Better practice

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components{
  .btn{
      @apply bg-transparent border  border-black hover:bg-black hover:text-white px-6 py-2 rounded-2xl;
    }
}

see the example on tailwind PLAY

Related