Search code examples
tailwind-csstailwind-ui

Can I create a custom class with arbitrary values Tailwindcss


I want to create a class in Tailwindcss with arbitrary values for example

HTML

<button class="my-custom-class[#fff]" />

CSS

@layer componenets {
  .my-custom-class {
    @apply bg-[--here-arbitrary-value]; /** the value is #fff */
  }
}

Solution

  • You can but not using layer components

    You need to write simple plugin for that

    tailwind.config.js

    const plugin = require('tailwindcss/plugin')
    const flattenColorPalette = require('tailwindcss/lib/util/flattenColorPalette')
    
    module.exports = {
      theme: {
        extend: {
          colors: {
            from: {
              config: {
                500: 'yellow', // for example purposes
              },
            },
          },
        },
      },
      plugins: [
        plugin(function ({ matchUtilities, theme }) {
          matchUtilities(
            {
               // Class name
              'my-custom-class': (value) => {
                return {
                  backgroundColor: value, // Desired CSS properties here
                  color: theme('colors.white') // Just for example non-dynamic value
                }
              },
            },
            // Default values.
            // `flattenColorPalette` required to support native Tailwind color classes like `red-500`, `amber-300`, etc. 
            // In most cases you may just pass `theme('config-key')`, where `config-key` could be any (`spacing`, `fontFamily`, `foo`, `bar`)
            { values: flattenColorPalette(theme('colors')) } 
          )
        }),
      ],
    }
    

    Now you can use it like

    <div class="my-custom-class-[#000] my-4 p-6">JIT as HEX</div>
    
    <div class="my-custom-class-[red] my-4 p-6">JIT as string</div>
    
    <div class="my-custom-class-[rgb(0,0,0)] my-4 p-6">JIT as RGB</div>
    
    <div class="my-custom-class-blue-500 my-4 p-6">Using Tailwind Colors</div>
    
    <div class="my-custom-class-from-config-500 my-4 p-6 text-black">Using extended colors from config. NOTE: `text-black` doesn't applied!</div>
    

    NOTE: your class will take precedence over basic Tailwind classes

    <div class="bg-red-500 my-custom-class-[yellow]">
      This has yellow background
    </div>
    

    More about writing plugins here

    DEMO