How to do gradient text with Tailwind CSS
August 29, 2022
In Tailwind CSS v3, gradient text has become a lot easier, here’s how to do it.
Step 1: Add your gradient styles
<h1 class="bg-gradient-to-r from-blue-600 via-green-500 to-indigo-400">
Here are the official docs on how to work with gradients in Tailwind but to break it down:
bg-gradient-to-rcreates the gradient and makes it from left to right
from-blue-600sets our starting color, which will go on the left
via-green-500sets our middle color, which is optional
to-indigo-400sets our ending color, which will go on the right and can be optional if you want the end to be transparent
You can change these values to whatever suit your use case but this is the most common structure for working with gradients in Tailwind CSS
Optional but recommended
At this point, you may have noticed an issue with your code: if your text is short enough and you resize your window to a lower width, the text will move over the gradient colors.
This will cause an issue when you have the finished gradient text code. When you resize your window, the gradient colors in your text will change.
This is because the gradient we created takes up the full width of the element instead of the width of the text.
To fix this, all we need to do is add the
inline-block class to our element.
<h1 class="... inline-block">
Now, the gradient takes up only the width of the text, instead of the width of the parent element.
Problem solved! Now, let’s move on to the next step.
Step 2: Make your text transparent
Make your text transparent using the
<h1 class="... text-transparent">
The text will disappear but don’t worry, we’ll fix that in the next step.
Step 3: Clip the text to the background
This is the most important thing for making gradient text, it uses the background-clip CSS property, which has multiple values and one of them is
text, to use that specific property and value in Tailwind CSS we just need to add the
<h1 class="... bg-clip-text">
That’s it! We now have our gradient text 🥳
Putting it all together you get this snippet:
<h1 class="bg-gradient-to-r from-blue-600 via-green-500 to-indigo-400 inline-block text-transparent bg-clip-text">hello world</h1>
Here’s the Tailwind Play link if you want to play around with it.
That’s it for this one! I hope you learned how to make gradient text with Tailwind CSS and how to take into account how the width of the text changes the gradient colors and how to fix it.