Pro Tailwind

01. Define colors as CSS variables

🐇 TL;DR

  • We’re currently not doing any theming with our extended colors
  • Let’s define these colors as CSS variables, so they can change from theme to theme!

⬇️ Skip to the challenge


🐢 Background

As we just noted, our current implementation of extra colors has nothing to do with theming.

Right now, we’re just defining three new colors in our Tailwind config:

// tailwind.config.js
const themes = {...}

module.exports = {
  theme: {
    extend: {
      colors: {
        base: themes.base.colors,
        rainforest: themes.rainforest.colors,
        candy: themes.candy.colors,
      },
    },
  },
}

There is no theming happeneing at all here. We’ve just extended our theme with new colors.

Each color is generating new, different utility classes. Like bg-rainforest-500, or text-candy-800.

Those colors have a “hardcoded” value baked in their name. One specific value.

What we want is to be able to use the same color utility class across all themes.

We need a name that makes sesnse regardless of what color that utility class represents. A semantic color name.

We should be able to redefine that color based on the currently active theme.

To do this, let’s leverage the power of CSS custom properties, or CSS variables.


🏆 Your first challenge 🏆

In the Tailwind Play below, implement a primary-500 color that works across all themes.

Here are a few steps to guide you:

  1. In the CSS tab, define a --primary-500 CSS variable. Do this at the :root scope.

  2. In the Config tab, extend the colors object with a new primary color, with a 500 shade that uses the --primary-500 CSS variable.

  3. Redefine this --primary-500 variable within theme scopes. You’ll need to work out what those scope selectors should be!

  4. Extra 🌶: If you got it working, repeat the process for the rest of the 50 to 900 shades.

Don’t worry about code duplication for now. Let’s start by making it work. Copy & paste like there is no tomorrow!

You’ll find more hints within the Play.


✌️ Good luck!

Start challenge