How do I create a wave text effect with CSS?
A wave that passes over the words one after another gives a headline a clear rhythm. In Arabic we move whole words, because a letter changes shape by its position in the word, and splitting a word into letters breaks the joins.
Steps
- Make the headline a flex container with flex-wrap and gap, so word order is correct in both RTL and LTR.
- In JavaScript, split the text on spaces only (split(/\s+/)), put each word in a span and store its index in the variable --i.
- Make each span inline-block and move it up and down with translateY in keyframes.
- Delay each word by --i x 0.15s with animation-delay.
- Put the full sentence in aria-label on the heading and aria-hidden on the pieces, and stop the motion under prefers-reduced-motion.
Sources
- MDN: animation-delay sets how long to wait before the animation starts: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-delay
- MDN: translateY() moves an element vertically: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translateY
- 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: Arabic letters change shape by position, so animate whole words: 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: #101828; color: #fff; }
.wave { display: flex; flex-wrap: wrap; gap: .35em; justify-content: center;
font: 800 clamp(1.8rem, 7vw, 3.5rem)/1.5 system-ui, "Segoe UI", Tahoma, sans-serif; margin: 0; }
.wave .w { display: inline-block; animation: bob 1.6s ease-in-out infinite; animation-delay: calc(var(--i) * 0.15s); }
@keyframes bob { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-.3em); } }
@media (prefers-reduced-motion: reduce) { .wave .w { animation: none; } }
</style>
<h1 class="wave" id="t">أهلا بك في عالم الحركة</h1>
<script>
const el = document.getElementById('t');
const text = el.textContent.trim();
el.setAttribute('aria-label', text); // screen readers read the full sentence
el.textContent = '';
text.split(/\s+/).forEach((word, i) => { // split on spaces only: whole words
const s = document.createElement('span');
s.className = 'w';
s.setAttribute('aria-hidden', 'true');
s.style.setProperty('--i', i);
s.textContent = word;
el.appendChild(s);
});
</script>
</html>can't find the motion you need? Request it here
Related articles: