Generating Stitches Variants For Each Color Of Your Theme

Konstantin Münster
3 min readAug 22, 2022

Stiches.dev lets you write performant CSS-in-JS. Let’s see how we can speed up creating variants with your color palette!

Applying our trick, we can generate color variants easily for all colors in our palette.

I recently came across Stitches.dev when I rebuilt my portfolio. Using a CSS-in-JS library with almost zero interpolations at runtime and a very well designed API seemed appealing — so I tried it!

What are Variants in Stitches?

A feature Stitches offers are variants. This is one of its key differences compared to Styled Components, which was one of the first and still most popular CSS-in-JS tools. Whereas Styled Components used string interpolation to conditionally set styles, Stitches lets you predefine variants to avoid unnecessary interpolation. This significantly enhances performance.

A simple example can be found in this Stitches docs:

Using Your Theme’s Color Palette To Create Variants

When I built my portfolio, I wanted to have such a variant-based button component too. But I wanted it to be highly customizable — instead of having two defined color variants, it should accept any color that I defined in my theme’s color palette.

The Manual Way

The easiest (and probably fastest 😄) way would have been to manually create a variant for each color I used in my theme. So something like this:

This would have been perfectly fine but I was eager to automate this process so that I could reuse the same functionality in other components too.

The Automated Way

Since Stitches uses an object syntax to write CSS, we can write a function that generates an object that…

Konstantin Münster

Writing about Web Development and Freelancing. // konstantin.digital

Recommended from Medium

Lists

See more recommendations