skip to Main Content

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 ?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Define the colour as three separate CSS variables (h,s,l) then change the local value of l on hover:

    :root {
      --h: 193;
      --s: 55%;
      --l: 40%;
      --lhover: 35%; /* you could do calc(var(--l) - 5%) here but why bother? */
    }
    
    p {
      background-color: hsl(var(--h), var(--s), var(--l));
    }
    
    p:hover {
      --l: var(--lhover);
    }
    <p>hover me</p><p>hover me</p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search