Fade/transition tailwind class to something else over certain amount of time?
Asked Answered
W

2

19

Is there a way to set bg-red-300 and fade/transition it to bg-transparent or different bg class over 2 seconds or do I need javascript for this? I want an element to highlight and then return to normal after 2 secs. Thank you!

Wilson answered 8/7, 2021 at 17:46 Comment(0)
S
48

You may create your own animation with config file

module.exports = {
  mode: 'jit',
  theme: {
    extend: {
      
      // that is animation class
      animation: {
        fade: 'fadeOut 5s ease-in-out',
      },

      // that is actual animation
      keyframes: theme => ({
        fadeOut: {
          '0%': { backgroundColor: theme('colors.red.300') },
          '100%': { backgroundColor: theme('colors.transparent') },
        },
      }),
    },
  },
  variants: {},
  plugins: [],
}

Use it like

<div class="w-40 h-40 animate-fade"></div>

Demo

P.S. However you may probably need some Javascript to trigger animate-fade classlist toggling or something as animation will proceed no matter does block is in viewport or not.

Sneeze answered 8/7, 2021 at 21:8 Comment(6)
Cool, very interesting solution. Thanks! Where can I learn more about what's available to put in the colors.red.300 part? I tried colors.red.300/50 and colors.red.300.50 for opacity but it didn't seem to work. Thank you!Wilson
It is basically javascript syntax of getting values by key in any theme object of config (Tailwind default included) - colors has key red, red has key 300. fadeOut animation in my example can be extracted with theme('keyframes.fadeOut') or theme(keyframes[fadeOut]). About second part - nice question short syntax was introduced at 2.2 and I believe has place only on front part as it is not registered in config. The only option I see is to pass standard CSS rgba() where red.300 should be present in RGB value but it's not cool...Sneeze
Ah thanks! So instead of theme('colors.red.300') I would do something like rgba(x, x, x, 0.5) ? I just tried and got Tailwind CSS: rgba is not definedWilson
Blockquote it like { backgroundColor: "rgba(x,y,z,a)" }. It thinks it is JS function which is not. You need to pass it as a stringSneeze
Posted your answer (with attribution) here: https://mcmap.net/q/665091/-how-to-fade-text-background-color-using-tailwindcss-without-hover-or-other-state-changes-to-trigger Thanks!Wheelman
What if i need to do fade in and fade out at the same elementSodden
M
20

You could utilize tailwind transition property

transition-opacity

<div class="h-8 w-8 bg-blue-600 transition-opacity ease-in duration-700 opacity-100 hover:opacity-0"></div>

refer https://tailwindcss.com/docs/transition-property

Demo

Mareld answered 10/5, 2022 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.