CSS Color Tricks

Written — Updated
  • Author: Una Kravetz
  • Source: https://www.youtube.com/watch?v=VD108ccVDSY
  • You can get a lot of flexibliity in color management by breaking HSL colors into a single CSS variable for each of H, S, and L.
  • Lightening and Darkening
    • Simple effects just use calc to alter one or more attributes.
    • .bright {
        color: hsl(
          var(--color-h), 
          var(--color-s),
          calc(var(--color-l) + var(--lighten-factor))
        );
      }
      
  • Blending Colors
    • Create a new color where each of H, S, and L is the average of the attribute from the two colors.
    • .blend {
        color: hsl(
          calc((var(--color1-h) + var(--color2-h)) / 2),
          calc((var(--color1-s) + var(--color2-s)) / 2),
          calc((var(--color1-l) + var(--color2-l)) / 2),
        )
      }
      
  • Contrasting Text Color
    • This is a relatively simple hack but enough for a lot of cases.
    • Take the luminance of the background color and tweak it to get black or white.
    • label {
        --contrastThreshold: 60%;
        --switch: calc((var(--color-l) - var(--contrastThreshold)) * -100);
        color: hsl(0, 0,var(--switch));
      }
      

Thanks for reading! If you have any questions or comments, please send me a note on Twitter.