How to Change SVG Color with Tailwind CSS
By Nihar Ranjan Das, Published on July 6th 2023 | 5 mins, 416 words
Nowadays, Tailwind CSS has brought a revolutionary change in web design. For me, before Tailwind CSS, Web design was so boring and so depressing. But now I feel so comfortable and always love to work on web design tasks.
There are so many things to talk about Tailwind CSS but in this article, we will talk about particularly how to modify SVG color using Tailwind CSS.
Let's dive deep and learn how to design SVG using Tailwind CSS
The basic coloring of SVG, can be done by setting to attributes on the node: fill and stroke. Using fill we can paint the color inside the object and using stroke we can set the color of line around the object.
For example:
<rect x="10" y="10" width="100" height="100" stroke="blue" fill="purple"/>
We can customise the fill and stroke using CSS also.
<rect x="10" y="10" width="100" height="100" style="stroke: black; fill: red"/>
In Tailwind CSS, there are two type of utility classes for styling SVG
- Fill
- Stroke
There are so many utility classes to customise the fill and stroke attribute's value in Tailwind CSS. We can set fill and stroke color, make reactive with state change, customise design in different breakpoint and so on.
Change the fill/stroke color
Using the fill-{color} format, we can easily change the fill color of an SVG. Same format for stroke
<svg class="fill-indigo-600 ..."> <!-- ... --> </svg>
Change the fill/stroke color in different state
In Tailwind, you can apply utility classes conditionally in different states using variant modifiers. For example, using hover:stroke-indigo-700, we can change the stroke color stroke-indigo-700 utility on hover. Same format for fill
<svg class="stroke-indigo-600 hover:stroke-indigo-700 ..."> <!-- ... --> </svg>
Change the fill/stroke color in different breakpoint
There are also variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, using md:fill-indigo-700, we can change the fill color fill-indigo-700 utility at only medium screen sizes and above.
<svg class="fill-indigo-600 md:fill-indigo-700 ..."> <!-- ... --> </svg>
Change the fill/stroke color using Arbitrary value
If you want to set a custom color which is not included in your theme color, use square brackets (fill-[#color-code]) to generate a property on the fly using any arbitrary value.
<svg class="fill-[#212c3a] ..."> <!-- ... --> </svg>