Skip to content
Search

Tailwind:Colors

lastmod 2024-03-12created 2023-03-162 edits

Naming your colors

By default, Tailwind uses literal color names (like red, green, etc.) and a numeric scale (where 50 is light and 900 is dark). We think this is the best choice for most projects, and have found it easier to maintain than using abstract names like primary or danger.

That said, you can name your colors in Tailwind whatever you like, and if you're working on a project that needs to support multiple themes, for example, it can make sense to use more abstract names.

module.exports = {
  theme: {
    colors: {
      primary: '#5c6ac4',
      secondary: '#ecc94b',
      // ...
    }
  }
}

Using CSS variables

If you’d like to define your colors as CSS variables, you’ll need to define those variables as just the color channels if you want them to work with the opacity modifier syntax:

Define your CSS variables as channels with no color space function

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --color-primary: 255 115 179;
    --color-secondary: 111 114 185;
    /* ... */
  }
}

WARNING

Don’t include the color space function or opacity modifiers won’t work. like --color-primary: rgb(255 115 179);

Then define your colors in your configuration file, being sure to include the color space you’re using, and the special <alpha-value> placeholder that Tailwind will use to inject the alpha value when using an opacity modifier:

/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    colors: {
      // Using modern `rgb`
      primary: 'rgb(var(--color-primary) / <alpha-value>)',
      secondary: 'rgb(var(--color-secondary) / <alpha-value>)',

      // Using modern `hsl`
      primary: 'hsl(var(--color-primary) / <alpha-value>)',
      secondary: 'hsl(var(--color-secondary) / <alpha-value>)',

      // Using legacy `rgba`
      primary: 'rgba(var(--color-primary), <alpha-value>)',
      secondary: 'rgba(var(--color-secondary), <alpha-value>)',
    }
  }
}

When defining your colors this way, make sure that the format of your CSS variables is correct for the color function you are using. You’ll want to use spaces if using the modern space-separated syntax, and commas if using legacy functions like rgba or hsla:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    /* For rgb(255 115 179 / <alpha-value>) */
    --color-primary: 255 115 179;

    /* For hsl(198deg 93% 60% / <alpha-value>) */
    --color-primary: 198deg 93% 60%;

    /* For rgba(255, 115, 179, <alpha-value>) */
    --color-primary: 255, 115, 179;
  }
}

See also

Favorite site

author Zer0 sitemap