I wanted to make a hover effect that looked like the user’s cursor was a light source that was casting a directional shadow against some text. I’m sure there are fancier ways to do this, but by writing some CSS and jQuery I came up with this:
See the Pen Sequential Letter Animation Starter Pen by Braad Martin (@BraadMartin) on CodePen.0
It’s built with three main pieces. First, my span-letters.js script to wrap each letter of a string in a span with a class to indicate its position in the string. Then some jQuery to add a class to the wrapper indicating which letter is being hovered. Finally, a bunch of CSS to handle the text-shadows used to create the directional shadow.
I used the nesting power of Sass to keep everything DRY. Here’s the CSS for the center position:
#target.l5 { .sl1 { text-shadow: -8px 4px 8px #444444; } .sl2 { text-shadow: -6px 4px 8px #444444; } .sl3 { text-shadow: -4px 4px 8px #444444; } .sl4 { text-shadow: -2px 4px 8px #444444; } .sl5 { text-shadow: 0px 4px 8px #444444; } .sl6 { text-shadow: 2px 4px 8px #444444; } .sl7 { text-shadow: 4px 4px 8px #444444; } .sl8 { text-shadow: 6px 4px 8px #444444; } .sl9 { text-shadow: 8px 4px 8px #444444; } }
The key is that each letter gets a more intense shadow the further away it is from the letter being hovered. A simple transition on the spans ties the whole thing together and gives it a sense of response as you quickly hover across the letters.
With the structure in place, it’s easy to create variations. I’ve always been a sucker for 3D text effects, so I had to try an inset shadow:
See the Pen Sequential Letter Animation Starter Pen by Braad Martin (@BraadMartin) on CodePen.0
The shadow was fun, but I still wasn’t getting that feeling of the light coming from the cursor and shining on the top of the letters. I decided to try adding a color change, and to make it flexible and achieve additional DRYness I created Sass mixins for each letter based on how far it was from the target letter:
See the Pen Sequential Letter Animation Starter Pen by Braad Martin (@BraadMartin) on CodePen.0
Not bad. I made the color change noticeably dramatic to illustrate the effect. A more subtle color change would definitely add some realism.
With the mixins in place I can easily add more CSS properties to each letter. My next move will be to add mixins for each letter based on the direction AND how far it is from the hovered letter, which will allow me to keep all the CSS properties including the text-shadows in a clean set of mixins. That will make it much easier to try out new ideas very quickly. Sass is a life saver in these kinds of situations.
-Braad