15

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!

SeaBass
  • 1,584
  • 4
  • 20
  • 46

2 Answers2

38

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.

Ihar Aliakseyenka
  • 9,587
  • 4
  • 28
  • 38
  • 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! – SeaBass Jul 09 '21 at 03:42
  • 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... – Ihar Aliakseyenka Jul 09 '21 at 06:50
  • 1
    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 defined` – SeaBass Jul 09 '21 at 16:34
  • 1
    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 string – Ihar Aliakseyenka Jul 09 '21 at 17:08
  • Posted your answer (with attribution) here: https://stackoverflow.com/a/71449617/1459653 Thanks! – Mark Gavagan Mar 12 '22 at 12:25
12

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

Jay Killeen
  • 2,832
  • 6
  • 39
  • 66
Shabeer Ali
  • 903
  • 11
  • 20