Darken or lighten the background color in CSS using color-mix() and oklch()

X @urre

One of the last pieces when moving a Sass codebase to vanilla CSS was to replace the darken() and lighten() color functions in Sass. Now it’s easier than before. There are good browser support for both color-mix() and the oklch() color space. Both works across the latest devices and browser versions since 2023. A quick example:

Demo

Darken or lighhten background colors in CSS using color-mix() and oklch()

/* Darken background color in CSS, two options
Instead of using Sass lighten() and darken()
Urban Sanden 2024
*/

@layer demo;

@layer demo {
  :root {
    --first-color: hotpink;
    --second-color: slateblue;
    --third-color: dodgerblue;
    --fourth-color: brown;
  }

  .buttons {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 1rem;
  }

  .first {
    background-color: var(--first-color);
  }

  .second {
    background-color: var(--second-color);
  }

  .third {
    background-color: var(--third-color);
  }

  .fourth {
    background-color: var(--fourth-color);
  }

  .first:hover {
    /*
  The color-mix() functional notation takes two <color> values and returns the result of mixing them in a given colorspace by a given amount.
  https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color-mix
  */
    background-color: color-mix(in srgb, var(--first-color), #000 20%);
  }

  .second:hover {
    /*
  The oklch() expresses a given color in the Oklab color space. oklch() is the cylindrical form of oklab(), using the same L axis, but with polar Chroma (C) and Hue (h) coordinates.
  https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklch
  */
    background-color: oklch(from var(--second-color) calc(l - 0.2) c h);
  }

  .third:hover {
    /*
Lighten
  */
    background-color: color-mix(in srgb, var(--third-color) 60%, white);
  }

  .fourth:hover {
    /*
Lighten
  */
    background-color: oklch(from var(--fourth-color) calc(l + 0.2) c h);
  }
}