Salesforce, Python, SQL, & other ways to put your data where you need it

Need event music? 🎸

Live and recorded jazz, pop, and meditative music for your virtual conference / Zoom wedding / yoga class / private party with quality sound and a smooth technical experience

Growing link underline, in Tailwind CSS

15 Jun 2021 🔖 web development
💬 EN

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. See it on Tailwind Play or keep reading to just see the source code here.

You need to use a gradient from a color to itself so that your background is a “background image,” not a “background color.”

<p>I am some text, and <a class="bg-gradient-to-r from-yellow-200 to-yellow-200 bg-growing-underline" href="https://example.com">I am a link</a>, and that's that.</p>

The rest of the party tricks, you can wrap up by making yourself a new Tailwind class in your tailwind.css file (or whatever you call it):

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer utilities {
  .bg-size-2em {
    background-size: 100% 0.2em;
  }
  .bg-hundred {
    background-size: 100% 100%;
  }
  .bg-near-bottom {
    background-position: 0 88%;
  }
  .bg-growing-underline {
    @apply bg-no-repeat bg-near-bottom bg-size-2em transition-all duration-200 hover:bg-hundred focus:bg-hundred;
  }
}

Alternatively, if you feel cleaner not exposing intermediate concepts like bg-size-2em, bg-hundred, and bg-near-bottom to yourself for reuse elsewhere in your HTML (see on Tailwind Play):

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer utilities {
  .bg-growing-underline {
    background-size: 100% 0.2em;
    background-position: 0 88%;
    @apply bg-no-repeat transition-all duration-200;
  }
  .bg-growing-underline:hover {
    background-size: 100% 100%;
  }
  .bg-growing-underline:focus {
    background-size: 100% 100%;
  }
}

Note that 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.


Update: Ben says he grabbed the code from Morgan Wesemann.

--- ---