Growing link underline, in Tailwind CSS
15 Jun 2021
Table of Contents
Today I learned that Learn 11ty From Scratch opened up for free. Searching for the news, I found Ben Myers’ article “I Finally Understand Eleventy’s Data Cascade,” which reminded me how much I like some of his styling, including links whose underlines are chunky and grow to be full backgrounds when you hover or focus on them.
I’ve been doing a lot of Tailwind lately on landing-page-type sites so I can rip off other peoples’ components, but I hadn’t found a link style I was satisfied with, so I ported Ben’s work to Tailwind.
Ben’s rising style
You need to use a gradient from a color to itself so that your background is a “background image,” not a “background color.”
Now that Tailwind 3 introduced arbitrary properties, the appropriate code would be something along the lines of:
<p>
I am some text, and then
<span
class="
bg-gradient-to-r from-yellow-200 to-yellow-200
bg-no-repeat [background-position:0_88%]
[background-size:100%_0.2em]
motion-safe:transition-all motion-safe:duration-200
hover:[background-size:100%_100%]
focus:[background-size:100%_100%]
"
>I am some fancy-underlined text</span>,
and I am normal text again.
</p>
Note: You can’t use bg-cover
for the hover/focus, even though it looks the same as background-size: 100% 100%
, because the smooth background size transition only works with an explicit size.
If you’d like to do something like use this as a default link style in Tailwind Typography prose
-classed HTML elements, I’ve added code to Tailwind Play to show how you can:
- Use
tailwind.config.js
to override Typography’s defaults with individual traits like boldfacing or de-underlining links, and - Use
tailwind.css
to set.prose a { @apply special-underline }
.
Question
As far as I can tell, there’s no @apply
equivalent in tailwind.config.js
. Does anyone know of one? It seems like it’d be nice to keep the definition of .prose a
in one file. See Tailwind Play for the example I’d like to “fix.”
Underline falling style
While it’s not the same thing as above, I personally find transitioning from this to this an equally respectable way to scream “this is a link!” to a reader.
The main difference is that the transition will grow “down” instead of “up.”
As of Tailwind 3, underline styles are now native commands, and you can use any underline thickness you like with arbitrary value square-bracket notation:
<p>
I am some text, and then
<span
class="
underline
decoration-yellow-500 decoration-[0.25rem]
motion-safe:transition-all motion-safe:duration-200
hover:decoration-[0.5rem] focus:decoration-[0.5rem] hover:decoration-yellow-500/50 focus:decoration-yellow-500/50
"
>I am some fancy-underlined text</span>,
and I am normal text again.
</p>
Credits
Update: Ben says he grabbed the code from Morgan Wesemann.