Search code examples
tailwind-csstailwind-uitailwind-in-jstailwind-variantstailwind-css-4

How to use @keyframes in Tailwind CSS version 4?


I just started learning Tailwind and I watched a tutorial. At first, the command npx tailwindcss init, which creates a file tailwind.config.js, didn't work for me. Error: Invalid command: init. This wasn't a problem, though, because I was able to use Tailwind classes normally. But when I wanted to create a keyframe, I saw that it should be created in tailwind.config.js.

I created the file manually and added the keyframe, but the keyframe didn’t work in the HTML.

// tailwind.config.js
module.exports = {
    purge: {
        content: ['./build/*.html', './build/js/*.js'],
        safelist: ['animate-open-menu'], // Ensure your custom animation isn't purged
    },
    theme: {
        extend: {
            animation: {
                // Custom animation using the defined keyframes
                'open-menu': 'open-menu .5s ease-in-out forwards',
            },
            keyframes: {
                // Custom keyframes definition
                'open-menu': {
                    '0%': { transform: 'scaleY(0)' },
                    '80%': { transform: 'scaleY(1.2)' },
                    '100%': { transform: 'scaleY(1)' },
                },
            },
        },
    },
    variants: {},
    plugins: [],
};

Solution

  • New configuration

    Use legacy JavaScript-configuration

    Starting from TailwindCSS v4, you can automatically use a CSS-first configuration. However, if you still want to use a tailwind.config.js similar to v3, follow "TailwindCSS v4 is backwards compatible with v3" steps with the @config directive.

    Use new CSS-configuration

    In the CSS-first setup, you can inject custom styles and @keyframes using the @theme directive.

    @import "tailwindcss";
    
    @theme {
      --animate-fade-in-scale: fade-in-scale 0.3s ease-out;
    
      @keyframes fade-in-scale {
        0% {
          opacity: 0;
          transform: scale(0.95);
        }
        100% {
          opacity: 1;
          transform: scale(1);
        }
      }
    }
    

    Some outdated configurations

    The corePlugins, safelist and separator options from the JavaScript-based config are not supported in v4.0.


    Source: Use the @config directive to load a legacy JavaScript-based configuration