Skip to content

Instantly share code, notes, and snippets.

@dandean
Last active January 6, 2020 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dandean/a0a6ede97c808a24eb42ecb6f54430e1 to your computer and use it in GitHub Desktop.
Save dandean/a0a6ede97c808a24eb42ecb6f54430e1 to your computer and use it in GitHub Desktop.
Given input CSS color, component parts are declared as CSS Custom Properties for use with rbg() and hsl() functions.
/**
* Defines a color as a CSS custom property, along with a custom property for
* all of the color's component parts in both RGB and HSL.
*
* Example:
*
* :root {
* @include defineColor("blue", #0000ff);
* }
*
*
* Produces:
*
* :root {
* --blue: #0000FF;
* --blue-r: 0;
* --blue-g: 0;
* --blue-b: 255;
* --blue-h: 240deg;
* --blue-s: 100%;
* --blue-l: 50%;
* }
*/
@mixin defineColor($name, $hex) {
--#{$name}: #{$hex};
--#{$name}-r: #{red($hex)};
--#{$name}-g: #{green($hex)};
--#{$name}-b: #{blue($hex)};
--#{$name}-h: #{hue($hex)};
--#{$name}-s: #{saturation($hex)};
--#{$name}-l: #{lightness($hex)};
}
@dandean
Copy link
Author

dandean commented Jan 6, 2020

Given this you can now use hsl() like so if you want to lighten or lighten the color by 15%:

.foo {
  color: hsl(var(--blue-h), var(--blue-s), calc(var(--blue-l) + 15%));
}

@dandean
Copy link
Author

dandean commented Jan 6, 2020

Another example, you can use CSS rgba() to modify the alpha opacity of a color:

.foo {
  color: rgba(var(--blue-r), var(--blue-g), var(--blue-b), 0.5)
}

@dandean
Copy link
Author

dandean commented Jan 6, 2020

You could also write your own SCSS functions to wrap this up into something like this, and then generate the output above:

.foo {
  color: set-opacity(--blue, 0.5);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment