Last active
November 25, 2024 10:06
-
-
Save Maxiviper117/2d6b9b82a39f73c334a586ea271515f1 to your computer and use it in GitHub Desktop.
Tailwind 4 Generate Color Shades Dynamically using chroma-js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from "fs"; | |
import chroma from "chroma-js"; | |
// Define your custom colors | |
const colors = { | |
primary: "#1E40AF", // Blue | |
secondary: "#10B981", // Green | |
tertiary: "#9333EA", // Purple | |
accent: "#F59E0B", // Amber | |
}; | |
// Function to generate shades for a given base color | |
function generateShades(baseColor) { | |
const scale = chroma | |
.scale(["white", baseColor, "black"]) | |
.domain([0, 0.65, 1]) | |
.padding([0.2, 0.2]) | |
.mode("oklch") | |
.colors(9); // Generates 9 shades for 100 to 900 | |
return { | |
base: baseColor, | |
100: scale[0], | |
200: scale[1], | |
300: scale[2], | |
400: scale[3], | |
500: scale[4], | |
600: scale[5], | |
700: scale[6], | |
800: scale[7], | |
900: scale[8], | |
}; | |
} | |
// Function to determine text color based on luminance | |
function getTextColorForBackground(color) { | |
const luminance = chroma(color).luminance(); | |
return luminance > 0.5 ? "black" : "white"; | |
} | |
// Generate the CSS | |
let css = '@import "tailwindcss";\n\n'; | |
css += "@theme {\n"; | |
Object.entries(colors).forEach(([name, baseColor]) => { | |
const shades = generateShades(baseColor); | |
Object.entries(shades).forEach(([key, shade]) => { | |
const textColor = getTextColorForBackground(shade); | |
css += ` --color-${name}-${key}: ${shade};\n`; | |
css += ` --color-${name}-text-${key}: ${textColor};\n`; | |
}); | |
}); | |
css += "}\n"; | |
// Write the CSS to a file | |
fs.writeFileSync("./tailwind-generated.css", css); | |
console.log("CSS with @theme block and text colors generated successfully!"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Generated output
tailwind-generated.css
Then import into entry css file for tailwindcss 4
main.css