Making a faded text effect in (mostly) CSS
I watched a video recently, that had text fading away. I thought it’d be cool to recreate that type of effect in CSS!
The final output:
See the Pen Fading away text effect by Cassidy (@cassidoo) on CodePen.
Other solutions
I initially thought I might do this very manually with :nth-child() selectors, which I think works well if you hard-code <span> tags around characters in a string. That would be a more “pure” CSS solution, but not nearly as flexible as what I would like!
Another way would be to use background-clip and a gradient, which looks cooler for paragraphs but not quite what I was going for:
.fading-text {
color: transparent;
background: linear-gradient(to right, #000 80%, rgba(0, 0, 0, 0.1) 100%);
background-clip: text;
}
This makes the text transparent so the background shows through, then adds a gradient background to the text that goes from opaque to transparent, then clips the background to the text. Again, looks cool, but I wanted a per-letter effect.
Final result
The CodePen embedded above describes what’s happening, but for posterity, here’s the same information but with some more details:
The fade() JavaScript function splits all of the characters in an element that has the class .fade-away. Then, it wraps each character with a <span>. Each of those <span>s has a class that assigns it a CSS variable based on its index:
<span style="--i:${letterIndex++}; --total:${total};">${char}</span>
Then, with the power of CSS calc(), it applies a blur filter and opacity based on those --i and --total variables!
This was fun, hope you liked it!