tailwind-csstailwind-css-4

How can I insert a custom layer between TailwindCSS's default base, components and utilities layers?


Although TailwindCSS has built-in layers with different levels of specificity, I'd like to declare my own custom layer. I want to set its priority higher than some TailwindCSS layers and lower than others.

This is what I tried:

/* input.css */
@import "tailwindcss";

@layer theme, base, custom, components, utilities;

But the result was duplication.

/* output.css */
@layer theme, base, custom, components, utilities;
@layer theme, base, components, utilities;

Solution

  • How to add custom layer

    Instead of @import "tailwindcss";, use the shorthand it provides:

    @layer theme, base, components, utilities;
    
    @import "tailwindcss/theme.css" layer(theme);
    @import "tailwindcss/preflight.css" layer(base);
    @import "tailwindcss/utilities.css" layer(utilities);
    

    You can customize this and insert new layers as needed.

    Solution CSS

    @layer theme, base, custom, components, utilities;
    
    @import "tailwindcss/theme.css" layer(theme);
    @import "tailwindcss/preflight.css" layer(base);
    @import "tailwindcss/utilities.css" layer(utilities);
    

    Now result will be:

    Generated CSS

    @layer theme, base, custom, components, utilities;
    

    Alternative without custom layer

    By the way, you can place your styles in the base layer too, right? Among all the base-level styles, the one added last will take precedence - so your custom code will always override preflight.css, assuming you load Preflight earlier.

    @layer theme, base, components, utilities;
    
    @import "tailwindcss/theme.css" layer(theme);
    @import "tailwindcss/preflight.css" layer(base);
    @import "tailwindcss/utilities.css" layer(utilities);
    
    @import "./mybase.css" layer(base);
    

    or

    @import "tailwindcss";
    
    @import "./mybase.css" layer(base);
    

    For components, the components layer can be an excellent choice following the same logic - and it's still lower in priority than utilities, meaning TailwindCSS classes will override it.

    @import "tailwindcss";
    
    @import "./mybase.css" layer(base);
    @import "./mycomponents.css" layer(components);
    

    or

    @import "tailwindcss";
    
    @layer base {
      * {
        padding: 2px;
      }
    }
    
    @layer components {
      .btn {
        background-color: var(--color-sky-500);
      }
    }