C.Tale
C.Tale

Reputation: 300

Is there a way to hook up an existing Tailwind class inside my own css declaration?

I'm not sure how to phrase this question properly. I'm learning Tailwind, I can't help but notice how dirty it is to write because of how the html can become a huge soup of different class combinations in an element, and I basically have to repeat them for every common element I basically write. I might be doing this wrong though so please correct me.

I was wondering if there's a way to put a css class inside a css declaration, possibly using css processors?

.this-button {
    .bg-red-500
    .rounded-lg
    .shadow-lg
    .animate-bounce
}

I'm pretty sure this is achievable with Javascript too. I was hoping for a solution using Sass, but anything would be great. What do you guys recommend would be a good practice for managing long Tailwind class combinations in elements?

Upvotes: 2

Views: 2605

Answers (2)

Kishieel
Kishieel

Reputation: 2053

In sass you can mix your classes in this way:

.some-class {
    @extend .bg-red-500
    @extend .rounded-lg
    @extend .shadow-lg
    @extend .animate-bounce
}

Now .some-class contains each properties from those classes.


In pure css you can use @apply directive. Example from tailwind docs.

.btn {
   @apply px-4 py-2 rounded font-semibold bg-gray-200 text-black;
}

Upvotes: 5

SangyK
SangyK

Reputation: 839

Yes, It is possible and done using 'Extracting Components'

Refer to this link, https://tailwindcss.com/docs/extracting-components

In the .css file where you have done the tailwind import, you can use the @apply directive.

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

@layer components {    
  .this-button {
     @apply bg-red-500 rounded-lg shadow-lg animate-bounce;
  }
}

For SASS refer to this link, https://tailwindcss.com/docs/using-with-preprocessors#using-sass-less-or-stylus

Upvotes: 1

Related Questions