Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readCSS

Generate hover colors with color-mix()

Use color-mix() to derive a hover background and border from a single brand color, with a plain-color fallback.

You change the brand blue on a button and the old hover color stays behind. The border has its own hex value too. Put the base color in one token and let CSS calculate the other two.

Mix a shade from the base token

Add a button with class="action", then load this stylesheet. The border mixes in more black than the hover background. Adjust the two percentages to tune each color.

.action {
  --brand: #2864dc;
  background: var(--brand);
  border: 2px solid var(--brand);
  color: white;
}

@supports (color: color-mix(in oklab, blue, black)) {
  .action {
    border-color: color-mix(in oklab, var(--brand) 76%, black);
  }

  .action:hover {
    background-color: color-mix(in oklab, var(--brand) 88%, black);
  }
}

You should see a blue button with a darker border and a background that darkens when you hover. Change --brand and inspect both states again. The mix follows the new color without another edit.

Read the percentages as shares

In the hover rule, 88% is the brand share. CSS gives the other color the remaining 12%. Move the brand share closer to 100% for a subtler change, or lower it to bring the mix closer to black.

in oklab tells CSS which color space to use for the mix. The same percentages can produce a different color with in srgb. See the color-mix specification.

Keep the @supports test if you move the mix into a custom property. The query tests the function in a declaration that expects a color. A custom property can store the function as raw tokens even when the browser cannot use those tokens as a color. The feature query keeps the base declarations in charge on that browser.

Check the states after changing the token

Open DevTools and force :hover so you can inspect the rendered background without holding the pointer over the button. Then change --brand in the style panel and read the computed background and border again. Both computed values should move with it.

A percentage specifies the mix, so check text contrast against the resulting background after a brand change. If you also use a light theme with a lighter base color, test that one with its actual text color. Check the focus outline against both backgrounds with the keyboard.