How do I make text with an animated gradient in CSS?
A gradient that moves inside the headline itself makes the first thing a visitor sees feel alive, with no image or video. The idea: paint the gradient as the text background, then move the background position. The whole line moves, so Arabic letters never break.
Steps
- Write a linear gradient that starts and ends on the same color, and make the background 300% wide so it has room to move.
- Clip the background to the text shape with background-clip: text, and make the fill transparent (-webkit-text-fill-color: transparent) so the gradient shows through the letters.
- Animate background-position from 0 to -300% in keyframes, linear and repeating.
- Add @media (prefers-reduced-motion: reduce) to stop the movement and keep a still gradient.
- Check that every color in the gradient has enough contrast against the page background, because the text no longer has one single color.
Sources
- MDN: background-clip: text paints the background clipped to the foreground text; also advises checking contrast: https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip
- MDN: background-position, the property the keyframes move: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/background-position
- MDN: prefers-reduced-motion detects a device setting to minimize non-essential motion; the reduce value is true when it is on: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
- Tahrikit: animate whole words or whole lines, never single Arabic letters: https://motion.velloxhq.com/en/learn/animate-arabic-text.html
The code
HTML
<!doctype html>
<html lang="ar" dir="rtl">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #0f1020; }
.grad-text {
margin: 0;
font: 800 clamp(2rem, 8vw, 4rem)/1.4 system-ui, "Segoe UI", Tahoma, sans-serif;
/* the gradient is wider than the text so it has room to move */
background: linear-gradient(90deg, #ff5f6d, #ffc371, #47c9e5, #ff5f6d);
background-size: 300% 100%;
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
color: transparent;
animation: flow 6s linear infinite;
}
@keyframes flow { to { background-position: -300% 0; } }
@media (prefers-reduced-motion: reduce) {
.grad-text { animation: none; background-position: 0 0; }
}
</style>
<h1 class="grad-text">حركة تبدأ من الكلمة</h1>
</html>can't find the motion you need? Request it here
Related articles: