Published on

How to Modify SVG Icon Colors with Tailwind CSS

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Modify SVG Icon Colors with Tailwind CSS

Changing the color of an SVG icon using Tailwind CSS is simple and efficient. You can use utility classes like fill-current and text-{color} to dynamically modify the color of your icons. This guide walks you through various methods of doing so.


Method 1: Using fill-current with text-{color}

When working with inline SVGs, you can set the fill color using fill-current, which inherits the text color:

<svg class="h-8 w-8 fill-current text-blue-500" viewBox="0 0 24 24">
  <path d="M5 3v18l15-9L5 3z" />
</svg>

In this example:

  • text-blue-500 sets the text color, which also applies to fill-current.
  • w-8 h-8 controls the icon size.

Method 2: Changing stroke Color

For stroke-based icons, use stroke-current instead:

<svg class="h-8 w-8 stroke-current text-red-500" fill="none" stroke-width="2" viewBox="0 0 24 24">
  <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
</svg>

Here, stroke-current makes the stroke color inherit from text-red-500.


Method 3: Using Tailwind with External SVG Files

If you're using an external SVG file (<img src="icon.svg">), Tailwind cannot directly modify the color. Instead, you can:

Option 1: Convert the SVG to Inline SVG

Instead of:

<img src="icon.svg" class="text-blue-500" />
<!-- This won't work -->

Do this:

<svg
  class="h-8 w-8 fill-current text-blue-500"
  xmlns="http://www.w3.org/2000/svg"
  viewBox="0 0 24 24"
>
  <path d="M5 3v18l15-9L5 3z" />
</svg>

Option 2: Modify the External SVG File

  • Open your icon.svg file in a text editor.
  • Remove any fill="color" attributes so Tailwind can control it.
  • Save and use it as an inline SVG.

If you're using Heroicons, simply use the provided Tailwind-compatible components:

<svg
  xmlns="http://www.w3.org/2000/svg"
  class="h-6 w-6 text-green-500"
  fill="none"
  viewBox="0 0 24 24"
  stroke="currentColor"
>
  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>

This method is ideal for frameworks like React or Vue.


FAQ

1. Why isn't my SVG color changing?

Ensure the fill or stroke attributes are removed from the SVG file. If it's an external file, use inline SVG instead.

2. Can I use bg-{color} for SVGs?

No, bg-{color} changes the background, not the icon color. Use fill-current or stroke-current instead.

3. How do I change the hover color?

Use Tailwind's hover: utility:

<svg class="h-8 w-8 fill-current text-gray-500 hover:text-red-500" viewBox="0 0 24 24">
  <path d="M5 3v18l15-9L5 3z" />
</svg>

Now, the icon changes to red on hover.