Naresh
Naresh

Reputation: 25813

Can tailwind colors be referenced from CSS?

I have some custom colors in my tailwind.config.js:

colors: {
  primary: {
    500: '#0E70ED',
    600: '#0552b3'
  }
}

I want to use them in my CSS files. Is there a way to replace #0e70ed below with primary-500?

.prose a.custom-link {
  color: #0e70ed;
}

Upvotes: 83

Views: 58105

Answers (3)

Ihar Aliakseyenka
Ihar Aliakseyenka

Reputation: 14323

Yes, you can use the theme() function.

Your colors

colors: {
  primary: {
    500: '#0E70ED',
    600: '#0552b3'
  }
}

will be available in CSS files as

.prose a.custom-link {
  color: theme('colors.primary.500');
}

More info here

Upvotes: 155

Spencer5051
Spencer5051

Reputation: 1085

With theme its also possible to get single source of truth using css variables and inside tailwind variables as follows. Thanks to Ihar Aliakseyenka for the answer.

(It seems like tailwind provides both the theme() and colors variable by default)

/* globals.css */
:root {
  --primary: theme(colors.slate.900);
  --secondary: theme(colors.slate.100);
}

And

// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        primary: "var(--primary)"
        secondary: "var(--secondary)"
      },
    },
  },
};

Then you can use

body {
  background-color: var(--primary);
  color: var(--secondary);
}

Or..

<div className='bg-primary text-secondary'> </>

And its all consistent

Upvotes: 6

kissu
kissu

Reputation: 46804

Why not directly use tailwind here ?

.prose a.custom-link {
  @apply text-primary-500;
}

If you want to access it in JS, you can use resolveConfig

import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from '@/tailwind.config.js'
const twFullConfig = resolveConfig(tailwindConfig)

...
mounted() {
  console.log('tw', twFullConfig.theme.colors['primary-500'])
}

Upvotes: 22

Related Questions