Mark Gavagan
Mark Gavagan

Reputation: 1172

How to fade text background color using TailwindCSS without hover or other state changes to trigger?

When new text conditionally appears, I want to call attention to it with a temporary amber background that becomes transparent 300ms after appearing (similar to what Stack Overflow does).

Screenshot when the text conditionally appears:

~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ initial view when text appears ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

And this what I'm trying to have 300ms later (text unchanged though):

~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ view after300ms ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

Thanks for any help.

Upvotes: 1

Views: 4690

Answers (1)

Mark Gavagan
Mark Gavagan

Reputation: 1172

This works!

Note: I put the background animation in a <span> tag, nested in the <p> tag, so the background doesn't stretch to full container width. There's probably a less hackey way to do that, but...

Code on the page (using TailwindCSS):

<p class="mb-2 text-slate-600">
      <span class="animate-fade rounded-lg text-sm font-normal">Text goes here</span>
        </p>

Code on Tailwind.config.js:

theme: {
    extend: {
      animation: {
        "fade": "fadeOut .9s ease-in-out",
      },

      // that is actual animation
      keyframes: (theme) => ({
        fadeOut: {
          "0%": { backgroundColor: theme("colors.amber.300") },
          "100%": { backgroundColor: theme("colors.transparent") },
        },
      }),

This is NOT my work. Answer stolen from this answer https://stackoverflow.com/a/68308652/1459653 posted by @IharAliakseyenka, to which I was directed by Twitter user @sandeshkumard

Upvotes: 6

Related Questions