How to style HTML text with color gradient using CSS
John Mwaniki / Updated on 07 Jul 2024The use of color gradients is one way of enhancing the visual presentation of text on an HTML page.
In this article, I will show you how to style HTML text with color gradients using CSS.
A color gradient is a gradual transition between two or more colors. With text, the color gradients can be used to add depth, texture, and visual appeal.
How to Style Text in HTML with Color Gradient Using CSS
We add a color gradient to text in HTML by using the background-clip
CSS property. It's used together with the background
(or background-image
) and color
properties.
We will style the H1 text below with the class "mytxt" to have a color gradient.
<h1 class="mytxt">Text With Color Gradient</h1>
The background
property adds a gradient in the background behind the text.
.mytxt{
background: linear-gradient(to right, #110230, #f2ec1f);
}
In this example, we have applied a linear gradient with two colors that start from the left and end on the right. You can change the direction by replacing "right" with "left", "top", "bottom", or even angle degrees (eg "45deg" for 45°). You can also use color names in place of color hex codes.
We then use the background-clip
property and assign it the value "text" to apply the gradient to the text.
.mytxt{
background-clip: text;
}
Lastly, we use the color
property with the value "transparent" to remove the fill from the text. This makes the text invisible and in turn, the gradient effect visible which results in a color gradient text.
.mytxt{
color: transparent;
}
Full Example:
HTML
<h1 class="mytxt">Text With Color Gradient</h1>
CSS
.mytxt{
background: linear-gradient(to right, #110230, #f2ec1f);
background-clip: text;
color: transparent;
}
Text With Color Gradient
More color gradient text examples:
Web Devs Planet
Sample Text Here
And Another Text
That's it.
Now you know how to add color gradients to text in HTML using CSS. You can now practice with different gradient colors, direction, and other properties to achieve the desired effect.