Lighten RGB with pure CSS
Asked Answered
B

1

6

Using pure CSS how can I lighten an RGB like: rgb(255, 0, 0)

SASS's lighten mixin works well: lighten(rgb(255, 0, 0), 25%) however it doesn't support CSS variables like this: lighten(var(--redColor), 25%)

I need to use CSS variables because you can change CSS variables on the fly after the page has loaded.

Things I've tried

  1. opacity: 0.75 - Opacity makes the background bleed into the color which I don't want.
  2. filter: brightness( - Filters affect the whole element but I just want to lighten specific colors.
  3. hsl(0, 100%, 50%) - HSL looks promising though I need a way to convert RGB to HSL in order to lighten the RGB.

Ideally I hope to have a SASS mixin that does some CSS to lighten whatever color's passed into it.

Billybillycock answered 21/3, 2021 at 21:35 Comment(5)
I think color manipulation is not yet supported in CSS3, but it is coming up in the CSS Color Module Level 4: w3.org/TR/css-color-4Amygdaloid
you want this to be applied to a background? there is a lot of way if it's the caseCorked
related: https://mcmap.net/q/1780454/-lighten-the-background-colour-from-another-class / https://mcmap.net/q/627759/-how-to-make-an-element-39-s-background-color-a-little-darker-using-css / https://mcmap.net/q/280564/-how-to-create-color-shades-using-css-variables-similar-to-darken-of-sassCorked
@TemaniAfif I need this to work for text color as well so things like filter and background-image won't work.Billybillycock
There’s a useful article on why use HSL instead of RGB here [link] elad.medium.com/why-css-hsl-colors-are-better-83b1e0b6eead The great thing there is that you can use CSS variables as each of the components and lightness makes sense which it sort of doesn’t in RGB.Krebs
B
4

This isn't possible.

However

Lightening colors is very easy with hsl so if you store the hsl color along with the RGB like this:

:root {
  --redColor: 142,  49,  42;
  --redColor_h: 4;
  --redColor_s: 54%;
  --redColor_l: 36%;
}

Then you can lighten the color with this SASS mixin:

@function lighten($shadeCode, $amount) {
  @return hsl(var(--#{$shadeCode}_h), var(--#{$shadeCode}_s), calc(#{var(--#{$shadeCode}_l)} + #{$amount}));
}

And use it like this:

background-color: lighten('redColor', 25%);

And boom you got lighter colors.

Billybillycock answered 24/3, 2021 at 1:0 Comment(2)
What about darken?Interrogative
@Interrogative It'd be the same function, except you'd minus #{$amount} instead of adding it.Billybillycock

© 2022 - 2024 — McMap. All rights reserved.