skip to Main Content

So in the code below, I have a --pop colour, and a --bg background color. I wish to calculate a hover color from the two as follows:

Mix --pop with the inverse with --bg.
e.g. if the background is black, I wish to mix --pop with white.
--bg could be any color.

--pop: #123456;
--bg: black;
--hover: color-mix(in srgb, var(--pop) 30%, ???inverse of --bg here???)

2

Answers


  1. If the JavaScript solution is okay you can try something like:

    const inverseColor = (color) => {
        color = color.substring(1);
        color = parseInt(color, 16);
        color = 0xFFFFFF ^ color;
        color = color.toString(16);           // convert to hex
        return `#${(`000000` + color).slice(-6)}`;    // pad with leading zeros
    };
    
    let color = getComputedStyle(document.documentElement)
                    .getPropertyValue('--bg');
    let inverseBG = inverseColor(color);        
    
    document.documentElement.style
        .setProperty('--bg-inverse', inverseBG);
    

    Then

    --hover: color-mix(in srgb, var(--pop) 30%, var(--bg-inverse));
    
    Login or Signup to reply.
  2. Here is a CSS only solution from the future using relative color syntax

    --pop: #123456;
    --bg: black;
    --hover: color-mix(in srgb, var(--pop) 30%, rgb(from var(--bg) calc(1 - r) calc(1 - g) calc(1 - b)))
    

    It has no support right now but soon you will be able to test it on Chrome

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search