RSS FeedTwitterMastodonShare IconHeart IconGithub IconArrow IconClock IconGUI Challenges IconHome IconNote IconBlog IconCSS IconJS IconHTML IconMedia IconGit IconSpeaking IconTools Icon
RGB and CMYK mixed with circles
A series of images of an avatar doing a bunch of skateboard tricks.

Use color-mix() to give opacity to opaque colors

4 min read
css

A very common task is to programmatically create non-opaque versions of brand colors. Comes in handy for hover effects, edge highlights, shadows, etc. Here's one way to achieve that with color-mix().

This post was prompted by Adam Wathan on Twitter:

The trick #

Ok browser, make red 25% opacity:

.make-transparent {
  background: color-mix(
    in oklab, 
    red, 
    transparent 75%
  );
}

To get that result, we mixed a 75% transparent hueless color with a fully opaque red, the result is a red at 25% opacity. 25% because specified in the mix that the transparent color is 75% dominant in the mix, leaving a remainder of 25% opacity for the red color.

Also, I chose oklab very specifically here, it gave me the mix I expected. Other color spaces did not. Glad I knew my color spaces.

Here's another one.

Make this 10% red, even more transparent. In fact, make it half as transparent as it is now.

.make-more-transparent {
  background: color-mix(
    in srgb, 
    rgb(255 0 0 / 10%), 
    transparent 50%)
  ;
}

Result is rgb(255 0 0 / 5%). See on Codepen.

Try it #

Chrome Canary, Firefox and Safari Tech Preview have color-mix(), we'll very likely see it cross browser by summer.

The better way #

Relative color syntax is much cleaner for this task.

It's also badass overall. Can't wait for it.

Make the red 25% opacity:

.make-transparent {
  background: rgb(from red r g b / 25%);
}

or the other example, you can either absolutely squash it by just setting it, or you can perform math on it, like cut it in half:

.squash-transparency {
  background: rgb(from rgb(255 0 0 / 10%) r g b / 5%);
}

or

.cut-transparent-in-half {
  background: rgb(from rgb(255 0 0 / 10%) r g b / calc(a / 2));
}

Resources #

  1. Try my color-mix tool at https://color-mix.style
  2. In depth color-mix() post at https://developer.chrome.com/blog/css-color-mix/
  3. Get more familiar with colorspaces at https://developer.chrome.com/articles/high-definition-css-color-guide/

Mentions #

Join the conversation on

58 likes
8 reposts
  • Benny Powers 🇨🇦️🇮🇱️
  • Евгений Резниченко
  • Pedro picapiedra
  • Rodri Alfonso
  • Will Browar 👨🏻‍💻
  • lukas.kllr
  • PawaOx4th
  • André Pinto

Member of a CSS Webring

Try a site in the ring!
PreviousRandomNext