Search code examples
nestedtailwind-csspostcsspostcss-import

TailwindCSS nesting not working with postCSS config


I am trying to scope tailwind styles and I am using this postcss config from Tailwind docs:

module.exports = {
plugins: {
  'postcss-import': {},
  'tailwindcss/nesting': {},
  tailwindcss: {},
  autoprefixer: {},
 }
}

and here is my css

.app-wrapper {
  @tailwind base;
  @tailwind components;
  @tailwind utilities;

 }

with this config the nesting is working fine but not all the tailwindCSS classes working as expected.

but when I change the config to the following

 module.exports = {
 plugins: [
     require('postcss-import'),
     require('tailwindcss/nesting'),
     require('tailwindcss'),
    require('autoprefixer'),
 ]
};

the classes works fine but the nesting throw the following error

Nested @tailwind rules were detected, but are not supported.

any idea how I can get the tailwind to work as expected with the nesting enabled?


Solution

  • If you wish to add parent selector for every compiled utility, add important: '.app-wrapper', into your tailwind config and do not wrap @tailwind directives

    // postcss.config.js
    
    module.exports = {
      plugins: {
        'postcss-import': {},
        'tailwindcss/nesting': {},
        tailwindcss: {},
        autoprefixer: {},
      }
    }
    
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    // tailwind.config.js
    
    module.exports = {
        important: '.app-wrapper',
        // ...
    };
    

    This called selector strategy. This way text-red-500 utility will be compiled as

    .app-wrapper .text-red-500 {
        --tw-text-opacity: 1;
        color: rgb(239 68 68 / var(--tw-text-opacity));
    }
    

    Please note: if you set darkMode as class strategy in your config

    module.exports = {
        darkMode: 'class',
        important: '.app-wrapper',
        // ...
    };
    

    utility dark:text-white (and every other dark utility) will be compiled as

    .app-wrapper .dark .dark\:text-white {
        --tw-text-opacity: 1;
        color: rgb(255 255 255 / var(--tw-text-opacity));
    }
    

    So if both dark and app-wrapper classes will be placed on the SAME element (e.g. html or body) dark mode would not work. That may explain why some classes are not working when using nesting