This is a solution for implementing color themes with tailwind. It makes use of CSS variables which are great providing that you don’t need to support IE11.

  1. module.exports = {
  2. theme: {
  3. colors: {
  4. teal: {
  5. 100: "var(--color-teal-100)",
  6. 200: "var(--color-teal-200)",
  7. },
  8. },
  9. },
  10. }

Those CSS variables that are referenced in the tailwind.config.js file then need to be created in CSS. With tailwind, your instinct might be to avoid CSS files altogether but I think of defining these variables more as configuration.

  1. :root {
  2. --color-teal-100: #55d3b8;
  3. --color-teal-200: #2c947e;
  4. }
  5. .funky-theme {
  6. --color-teal-100: #80f7dd;
  7. --color-teal-200: #5dd6bc;
  8. }

Anything under :root would be the default theme. To apply the funky-theme the class is used on a parent element then any children will use that theme.

  1. <body>
  2. <span class="text-teal-100">Pretty default themed in here</span>
  3. <section class="funky-theme">
  4. <span class="text-teal-100">All funky themed in here<span>
  5. </section>
  6. </body>

Primary, secondary (etc) approach

The last approach where we had CSS variables for specific colors like teal-100 might not be that useful when your themes actually use very different colors. It wouldn’t be ideal to have to override teal-100 with a red color.

Instead, you can name colors more generically.

  1. module.exports = {
  2. theme: {
  3. colors: {
  4. primary: "var(--color-primary)",
  5. secondary: "var(--color-secondary)",
  6. },
  7. },
  8. }
  9. :root {
  10. --color-primary: theme("colors.teal.100");
  11. --color-secondary: theme("colors.yellow.500");
  12. }
  13. .funky-theme {
  14. --color-primary: theme("colors.red.800");
  15. --color-secondary: theme("colors.green.500");
  16. }

Most likely with theming (e.g dark theme) this approach is going to be more useful.

A real-world example

I used this pattern for the theming on a “website builder” app where I wanted to use tailwind both for the “configuration” section and the “website preview” sections of the page.

I wanted each section to be independent so that the built websites colors didn’t get mixed up with the branding colors for the main application.

Tailwind theming with CSS variables - 图1

Similar to the examples earlier in the post I used both a :root theme and a website-preview theme.

  1. <body>
  2. <section>
  3. <h1>Single Product Store</h1>
  4. </section>
  5. <section class="website-preview">
  6. <h1>Barcardis Tea Shop</h1>
  7. </section>
  8. </body>

https://www.samdawson.dev/article/tailwind-theming