Home > Back-end >  Tailwind CSS custom addVariant plugin is not working
Tailwind CSS custom addVariant plugin is not working

Time:02-28

I'm trying to add a new variant called not-first to the Tailwind toolbelt, but when I try to use it, it doesn't work.

tailwind.config.js:

    const plugin = require('tailwindcss/plugin');

    module.exports = {
      mode: 'jit',
      purge: ['./src/**/*.{js,jsx}', './public/index.html'],
      darkMode: false, // or 'media' or 'class'
      theme: {
        extend: {},
      },
      variants: {
        extend: {},
      },
      plugins: [
        plugin(({ addVariant, e }) => {
          addVariant('not-first', ({ modifySelectors, separator }) => {
            modifySelectors(({ className }) => {
              const element = e(`not-first${separator}${className}`);
              return `.${element} > :not(:first-child)`;
            });
          });
        }),
      ],
    }

Usage:

    <li className={`not-first:bg-blue`}>{item.name}</li>

What am I doing wrong?

CodePudding user response:

It looks like you're apply the :not(:first-child) to the child of the element you're targeting with the not-first: pseudo-class.

:first-child should be applied to the child element itself (see: https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child).

To fix this, you could try changing

return `.${element} > :not(:first-child)`;

to

return `.${element}:not(:first-child)`;
  • Related