Home / Learn / How do I make text with an animated gradient in CSS?

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

  1. Write a linear gradient that starts and ends on the same color, and make the background 300% wide so it has room to move.
  2. 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.
  3. Animate background-position from 0 to -300% in keyframes, linear and repeating.
  4. Add @media (prefers-reduced-motion: reduce) to stop the movement and keep a still gradient.
  5. Check that every color in the gradient has enough contrast against the page background, because the text no longer has one single color.

Sources

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: