Search code examples
csstailwind-css

How to add new tailwind property class?


I am working on an app using tailwind, I want to add the image-rendering: pixelated class to a canvas element but I couldn't find how to do it in tailwind

I tried looking for image rendering tailwind classes but could not find any, Looking at the tailwind config documentation I only found how to implement this by creating a custom class for any image-rendering value possible

I would appreciate if you could help me implement a custom rendering-[render type] tailwind class which can be extended in the config file


Solution

  • You can use matchUtilities to create a utility class that accepts arbitrary values for image-rendering:

    const plugin = require('tailwindcss/plugin')
    
    /** @type {import('tailwindcss').Config} */
    export default {
      plugins: [
        plugin(function ({ matchUtilities }) {
          matchUtilities({
            rendering: (value) => ({
              'image-rendering': value,
            }),
          })
        }),
      ],
    }
    

    Now this:

    <div class="rendering-[pixelated]"></div>
    

    Generates the following CSS rule:

    .rendering-\[pixelated\] {
      image-rendering: pixelated;
    }
    

    Playground


    Note that you can also use the custom property syntax for this if you don't want to reuse this too many times:

    <div class="[image-rendering:pixelated]"></div>
    

    generates:

    .\[image-rendering\:pixelated\] {
      image-rendering: pixelated;
    }