Adding custom named colors generated by Tailwind

183 views Asked by At

Is there a way to assign custom colors in a way that allows Tailwind to generate meaningful semantic names?

For example, I'd like to have a collection of success colors that can be applied like this:

  • bg-success => Tailwind generates #F6FFED behind the scene
  • border-success => Tailwind generates #B7EB8F
  • text-success => Tailwind generates #135200
  • ... and so on

Update

Here's what I ended up doing but not sure if it's the best approach.

module.exports = {
  content: [...],
  theme: {
    extend: {
      backgroundColor: ({ theme }) => ({
        error: theme('colors.red.100'),
        info: theme('colors.blue.100'),
        success: theme('colors.green.100'),
        warning: theme('colors.gold.100'),
      }),
      borderColor: ({ theme }) => ({
        error: theme('colors.red.300'),
        info: theme('colors.blue.300'),
        success: theme('colors.green.300'),
        warning: theme('colors.gold.300'),
      }),
      textColor: ({ theme }) => ({
        error: theme('colors.red.900'),
        info: theme('colors.blue.900'),
        success: theme('colors.green.900'),
        warning: theme('colors.gold.900'),
      }),
    },
  },
  plugins: [...],
}

With that implementation, I am able to then recall generated colors I outlined in my question above.

  <div class="bg-success border-success text-success border-2">
    Hello world!
  </div>

But again, I'm not sure if this is the best approach.

1

There are 1 answers

1
eYinka On

Yes, all you need to do is update your tailwind.config.js file and extend the colors with your custom color needs. Here's an example of what you may be trying to do:

// tailwind.config.js
module.exports = {
  extend: {
    colors: {
      'success': '#00FF00',
    },
  },
}

And then in your markup, you can do things like

<div class="bg-success"> ABCD </div> or <p class="text-success"> Hello World! </p>.

Should definitely work!