A note to self on how to make HTML text with gradient background.
Introduction
I saw a cool text with animated gradient for text on Digital Ocean's Delploy conference site.
I wanted to know how it was implemented but didn't know how the gradient font was implemented in the first place.
An easy trick on CSS Tricks?
CSS-Tricks has a short article, Gradient Text, on how a gradient font is implemented.
h1 {
font-size: 72px;
background: -webkit-linear-gradient(#eee, #333);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
Source from CSS-Tricks article, Gradient Text.
As the CSS vendor prefix, -webkit
shows, it works for browsers like Chrome, Safari, or new Opera browsers (Works on FireFox on testing).
Webkit properties
- -webkit-linear-gradient: An easy way to implement a linear gradient (introduced in 2008).
-
-webkit-background-clip: Works on
text
clip while background-clip doesn't.- Even MDN uses
-webkit-background-clip
for the text clip demo.
.content { background-clip: text; -webkit-background-clip: text; color: transparent; }
- Even MDN uses
- ⚠ Provide a fallback
color
property incase the text clip doesn't work.-
-webkit-text-fill-color: This looks replaceable with
color
property.
-
-webkit-text-fill-color: This looks replaceable with
Animating the background
I have never used CSS animation and it requires declaring an animation as keyframes (a sequence?) and apply the animation on an HTML element using animation
specifying
e.g.) Demo on CodePen
HTML content
<span class="css-gnissy"
>NOVEMBER 10-11 • A FREE 24-HOUR GLOBAL CONFERENCE</span
>
CSS style
.css-gnissy {
background: -webkit-linear-gradient(
right,
red 20%,
green 40%,
blue 60%,
cyan 80%
);
-webkit-background-clip: text;
/*
`color` seems to work too
-webkit-text-fill-color: transparent;
*/
color: transparent;
background-size: 200% auto;
animation: shine 2s linear infinite;
}
@keyframes shine {
to {
background-position: 200% center;
}
}
animation: shine 2s linear infinite;
breaks down to
-
Keyframes name or animation-name:
shine
-
animation-duration:
2s
-
animation-timing-function:
linear
-
animation-iteration-count:
infinite
@keyframes
seems like a monster of its own so I will just add an MDN link to refer to later.
Tailwind Gradient Text
You can achive the gradient text effect with Tailwind CSS with bg-clip-text utility.
<div class="text-center text-5xl font-extrabold leading-none tracking-tight">
<span
class="bg-clip-text text-transparent bg-gradient-to-r from-teal-400 to-blue-500"
>
Hello world
</span>
</div>
Image by Lichtmagnet from Pixabay
Top comments (0)