Joshua
Joshua

Reputation: 5322

Lighten RGB with pure CSS

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.

Upvotes: 6

Views: 4577

Answers (1)

Joshua
Joshua

Reputation: 5322

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.

Upvotes: 4

Related Questions