tailwind-css

How to use tailwind's color on custom tailwind classes


I have created custom dropShadow classes. And I want to make it use Tailwind's color system like red-500 blue-200.

Current my config:

module.exports = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {
      dropShadow: {
        /* Adding all color I need is take so long!!! so I wanna use Tailwind's Color e.g red-500 blue-200 */
        'custom-red': '0 4px 6px rgba(255, 0, 0, 0.5)',
        'custom-green': '0 4px 6px rgba(0, 255, 0, 0.5)',
        'custom-blue': '0 4px 6px rgba(0, 0, 255, 0.5)',
      },
    },
  },
  plugins: [],
}

My goal is using it like:

<div class="drop-shadow-custom-red-500 p......"></div>
<div class="drop-shadow-custom-purple-600 p......"></div>
<div class="drop-shadow-custom-blue-200 p......"></div>

I know I can simply add each color to config when I need. but If I can use tailwind's color instead, It'll be more useful.


Solution

  • In the tailwind.config.js file, you can use plugins to achieve your desired result. You can use the following code:-

    const plugin = require("tailwindcss/plugin");
    const {default: flattenColorPalette,} = require("tailwindcss/lib/util/flattenColorPalette");
    
    export default {
      content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
      theme: {
        extend: {},
      },
    
      plugins: [
        plugin(function ({ matchUtilities, theme }) {
          matchUtilities(
            {
              "drop-shadow-custom": (value) => ({
                filter: `drop-shadow(20px 20px 20px ${value})`,
              }),
            },
            {
              values: flattenColorPalette(theme("colors")),
              type: "color",
            }
          );
        }),
      ],
    };