Categories
TailwindCSS Vue

Overriding Tailwind CSS Classes in VueJS Components

Example Scenario: Consider a Card.vue component with default Tailwind CSS styling.

<span class="hljs-tag"><<span class="hljs-name">template</span>></span>
  <span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-gray-200 p-4 rounded"</span>></span>
    <span class="hljs-comment"><!-- Card content --></span>
  <span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"></<span class="hljs-name">template</span>></span>

When attempting to change the background color in different instances, the default style is not overridden:

<span class="hljs-tag"><<span class="hljs-name">Card</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-blue-500"</span>></span><span class="hljs-tag"></<span class="hljs-name">Card</span>></span> <span class="hljs-comment"><!-- Expected to be blue, but remains gray --></span>

Solution: Prefix the Tailwind classes with ! when using the component to force override.

Implementation:

  1. No Change in Card.vue: Keep the component as it is.
  2. Usage with ! Prefix:

    Add the ! prefix to your Tailwind class when you use the component. This tells Tailwind to prioritize this class over others:

    <span class="hljs-tag"><<span class="hljs-name">Card</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"!bg-blue-500"</span>></span><span class="hljs-tag"></<span class="hljs-name">Card</span>></span> <span class="hljs-comment"><!-- Now it will be blue --></span>
    

Leave a Reply

Your email address will not be published. Required fields are marked *