Programmatic Color Generation for Tailwind CSS

Generate Tailwind-compatible color palettes programmatically using JavaScript and color science libraries.

generationalgorithmoklchautomation
advanced15 min readtutorial

Why Generate Colors Programmatically?

Hand-picking 11 shades for every brand color is tedious and inconsistent. Programmatic generation ensures uniform lightness steps, consistent saturation curves, and easy updates when a brand color changes.

Generating a Palette with JavaScript

import { oklch, formatHex } from 'culori';

function generatePalette(hue, chroma = 0.15) {
  const steps = [97, 93, 85, 75, 65, 55, 45, 38, 30, 22, 14];
  const names = [50,100,200,300,400,500,600,700,800,900,950];
  const palette = {};

  steps.forEach((lightness, i) => {
    const c = chroma * (lightness > 80 ? 0.3 : lightness < 30 ? 0.6 : 1);
    palette[names[i]] = formatHex(
      oklch({ l: lightness / 100, c, h: hue, mode: 'oklch' })
    );
  });
  return palette;
}

console.log(generatePalette(250)); // Blue-ish hue

Injecting into Tailwind Config

// tailwind.config.js
const { generatePalette } = require('./lib/colors');

module.exports = {
  theme: {
    extend: {
      colors: {
        brand: generatePalette(250, 0.15),
        accent: generatePalette(330, 0.18),
      }
    }
  }
};

Key Principles

  • Use oklch for even lightness distribution across the palette
  • Reduce chroma at very light and very dark ends to avoid clipping
  • Keep the hue constant or shift it slightly for warmer darks
  • Validate generated hex values fall within sRGB gamut for compatibility
  • Always check contrast ratios of generated 500-on-50 and white-on-600 pairs

Frequently Asked Questions

Which library should I use for color generation?

Culori is excellent for oklch manipulation. Chroma.js is another popular option. Both handle gamut mapping and format conversion.

How do I ensure generated colors are accessible?

After generating a palette, validate contrast ratios between adjacent shades. Ensure at least 4.5:1 between your text shade and background shade pairs.

Try Our Color Tools

50+ free tools for Tailwind CSS developers. No signup required.

Explore Tools