Skip to content

Instantly share code, notes, and snippets.

@mturnwall
Last active April 29, 2020 17:03
Show Gist options
  • Save mturnwall/1965c34dd03abcca576bdce14f27ab53 to your computer and use it in GitHub Desktop.
Save mturnwall/1965c34dd03abcca576bdce14f27ab53 to your computer and use it in GitHub Desktop.
Color Adjust Functions
import { hex, rgb } from 'color-convert';
/**
* Determine if a string is a hex color
* @param {string} color - hex representation of a color
* @returns {boolean}
*/
const isHexColor = color => /^#?(?:[a-f0-9]{3}){1,2}$/i.test(color);
/**
* Take a color and add transparency to it
* @param {string} color - color to convert
* @param {number} alpha - transparency amount for the color
* @returns {string} css `rgba()` string
*/
const rgba = (color, alpha = 1) => {
const rgb = isHexColor(color) ? hex.rgb(color) : [color];
return `rgba(${[rgb, alpha]})`;
};
/**
*
* @param {string} color color that needs to be adjusted
* @param {Object} [options] - options to adjust the color
* @param {number} [options.alpha=1] - add transparency to a color, 0-1
* @param {number} [options.lightness=0] - percentage to lighten a color, negative numbers will darken the color
*/
const colorAdjust = (color, { alpha = 1, lightness = 0 } = {}) => {
const [h, s, l] = isHexColor(color) ? hex.hsl(color) : rgb.hsl(color);
if (alpha !== 1) {
return rgba(color, alpha);
}
return `hsl(${h}, ${s}%, ${l + lightness}%)`;
};
$color-electric: #008ee2;
@function colorAdjust($color, $amt: 0) {
$hue: round(hue($color)) / 1deg;
$saturation: round(saturation($color));
$lightness: round(lightness($color-electric)) + $amt;
@return unquote('hsl(#{$hue}, #{$saturation}, #{$lightness})');
}
// example usage
h1 {
color: $color-electric;
background-color: colorAdjust($color-electric, -12);
&:hover {
color: colorAdjust($color-electric, -12);
}
&:active {
color: colorAdjust($color-electric, 28)
}
}
h1 {
color: #008ee2;
background-color: hsl(202, 100%, 32%);
}
h1:hover {
color: hsl(202, 100%, 32%);
}
h1:active {
color: hsl(202, 100%, 72%);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment