Search code examples
htmlcsscss-variableshslcss-calc

Calc with a multivalue css variable


I want to make a hover effect over a p-tag, when hovered the background should get darker. I used filter:brightness(85%) but this made also the text darker. Here is my css.

:root {
 --my-color:193 55% 40%
}

p { 
 background-color:hsl(var(--my-color)); 
}

/* This rule is not working */
p:hover {
 background-color:hsl(calc(var(--my-color)[2] - 5%))); 
}

Is there a possibility to subtract 5% only of the last element of my css variable ? Or do i have to split my variable into hue, saturation and lightness and then use calc on lightness ?


Solution

  • Yes, you can achieve this by breaking down your HSL variable into its individual components and then using calc for the hover effect. In your case, since you want to reduce the lightness by 5%, you would need to split the HSL value into its components.

    Here's how you can do it:

    :root {
      --hue: 193;
      --saturation: 55%;
      --lightness: 40%;
    }
    
    p {
      background-color: hsl(var(--hue), var(--saturation), var(--lightness));
    }
    
    p:hover {
      --new-lightness: calc(var(--lightness) - 5%);
      background-color: hsl(var(--hue), var(--saturation), var(--new-lightness));
    }
    

    This way, you're only modifying the --new-lightness variable on hover, keeping the other HSL components unchanged.

    Alternatively, you could calculate the new lightness directly in the calc function within the hover rule, like this:

    p:hover {
      background-color: hsl(var(--hue), var(--saturation), calc(var(--lightness) - 5%));
    }
    

    Both approaches achieve the same result, so you can choose the one that fits your preference or coding style.