2

Day 95: the color-mix() function

 1 year ago
source link: https://www.matuzo.at/blog/2023/100daysof-day95/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Day 95: the color-mix() function

posted on February 2., 2023

It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.


The color-mix() function takes two colors and returns the result of mixing them, in a given color space, by a specified amount.

To mix colors, pass the in keyword, followed by the color space, and 2 colors.

body {
background-color: color-mix(in srgb, blue, white);
}

The syntax is pretty straightforward, but the result is not so much. At least for someone like me who doesn’t understand color and color on the web very well. What surprised me specifically is that mixing colors in different color spaces can yield very different results.

:root {
--color1: blue;
--color2: white;
}

.a { --bg: color-mix(in srgb, var(--color1), var(--color2)); }
.b { --bg: color-mix(in srgb-linear, var(--color1), var(--color2)); }
.c { --bg: color-mix(in hsl, var(--color1), var(--color2)); }
.d { --bg: color-mix(in hwb, var(--color1), var(--color2)); }
.e { --bg: color-mix(in lch, var(--color1), var(--color2)); }
.f { --bg: color-mix(in oklch, var(--color1), var(--color2)); }
.g { --bg: color-mix(in lab, var(--color1), var(--color2)); }
.h { --bg: color-mix(in oklab, var(--color1), var(--color2)); }
<div class="a">srgb</div>
<div class="b">srgb-linear</div>
<div class="c">hsl</div>
<div class="d">hwb</div>
<div class="e">lch</div>
<div class="f">oklch</div>
<div class="g">lab</div>
<div class="h">oklab</div>
every resulting color is different. it's either a light or dark lilac color, blueish, pinkish or even green.

Each color will be mixed in equally. The resulting color will have 50% blue and 50% white. We can adjust that ratio.

body {
background-color: color-mix(in srgb, 30% blue, white);
/* Same as:
background-color: color-mix(in srgb, 30% blue, 70% white);
background-color: color-mix(in srgb, blue 30%, white);
background-color: color-mix(in srgb, blue, white 70%);
*/
}
The same colors, just a little lighter.

You can learn more about the function in Adam Argyle's fantastic article “CSS color-mix()”.

See on CodePen.

Further reading

Want more?

  1. Previous post: Day 94: the accent-color property

Overview: 100 Days Of More Or Less Modern CSS

My blog doesn't support comments yet, but you can reply via e-mail.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK