skip to Main Content

I’m trying to convert some LESS color functions (lighten/darken) to use the CSS color-mix function instead so that I can make use of CSS variables.

I have a dependency that uses these internally and have written an NPM post-install script that automatically converts them. The conversion is working fine, however the issue I’m facing is that the output is off.

Here is an example of the output:

enter image description here

For the color-mix, I’m using:

color-mix(in srgb, white 5%, var(--my-color)); // lighten(@mycolor, 5%);
color-mix(in srgb, white 50%, var(--my-color)); // lighten(@mycolor, 50%);

Any idea how can I more closely match what I’m seeing from LESS?

2

Answers


  1. Chosen as BEST ANSWER

    This will be possible once CSS Relative Colors (part of CSS Color Module 5) - currently only supported in Safari.

    background: hsl(from var(--color) h s calc(l + 5%));
    

    .colors {
      display: flex;
    }
    
    .colors > div {
      --color: #22b8cf;
      --color-lighten-5: #2ec5dd;
      width: 100px;
      height: 100px;
    
      &:nth-child(1) {
        background: var(--color);
      }
    
      &:nth-child(2) {
        background: var(--color-lighten-5);
      }
      
      &:nth-child(3) {
        background: hsl(from var(--color) h s calc(l + 5%));
      }
    }
    <div class="colors">
      <div>Base</div>
      <div>Less Lighten 5%</div>
      <div>CSS Lighten 5%</div>
    </div>


  2. LESS lighten() works on the luminance portion of the HSL colour value. See the docs here. So if your starting colour is #348298 which converts to hsl(193, 49%, 40%), then using LESS to lighten that by 50% means that 50% will be added to the luminance (last) value of this colour, so the resulting colour is hsl(193, 49%, 90%).

    You can replicate this in CSS by just using colours in HSL format and adjusting the luminance value. So you can use CSS variables for the hue and saturation components, but not the luminance.

    color-mix works quite differently, by blending two colours together in specified proportions. I’m sure you could find values which produce your desired colours by experimentation, but I don’t know how to do it mathematically.

    :root {
      --h1: 193;
      --s1: 49%;
    }
    body {
      display: flex;
      gap: 2px;
      font-family: sans-serif;
    }
    div {
      color: white;
      background-color: hsl(var(--h1), var(--s1), 40%); /* base colour */
      flex: 1;
      text-align: center;
      padding: 1em;
    }
    .m1 {
      background-color: hsl(var(--h1), var(--s1), 45%); /* five percent added to luminance */
    }
    .m2 {
      background-color: hsl(var(--h1), var(--s1), 90%); /* fifty percent added to luminance */
    }
    <div>Base</div>
    <div class="m1">add 5% luminance</div>
    <div class="m2">add 50% luminance</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search