Working with color: HSL first, RGB when necessary
A full application color system needs more than a handful of hex codes: it needs plenty of grays and a few primary hues, each with variants in brightness and saturation. Deriving those variants by hand from a single hue in a color picker is slow. HSL makes the job easier, and for RGB values there are conversion steps that keep hue and lightness fixed.
Declaring colors with HSL
HSL takes a hue from 0 to 360 together with percentages for saturation and lightness. Starting from a light, muted mint green:
div {
background-color: hsl(155, 30%, 80%);
}
Text that sits near black but matches the background can reuse the same hue and saturation and drop lightness to 5%:
div {
background-color: hsl(155, 30%, 80%);
color: hsl(155, 30%, 5%);
}
A call-to-action background can be made to stand out by raising saturation and lowering lightness slightly:
.call-to-action {
background-color: hsl(155, 80%, 60%);
color: hsl(155, 30%, 5%);
}
For secondary text, lowering saturation and raising brightness reduces contrast so it recedes. Contrast must still stay high enough for accessibility and readability, so lighten the background as well:
div {
background-color: hsl(155, 30%, 80%);
color: hsl(155, 30%, 5%);
}
.lessimportant {
color: hsl(155, 15%, 40%);
}
HSL is supported in all major browsers and is more declarative than RGB because hue, saturation and lightness are expressed separately.
When RGB is already in place
Several libraries convert HSL back to hex or RGB and add manipulation functions for building a color scheme:
- colvertize by Philipp Mildenberger — lightweight, many conversion methods plus a few manipulation methods.
- color, maintained by Josh Junon — declare, process and extract colors through a fluent interface, with a range of conversions and manipulations.
- TinyColor by Brian Grinstead (Mozilla) — accepts many input types, offers utility functions and helpers for generating color schemes.
CSS-Tricks also covers converting between color formats in JavaScript. For trying variations visually, the author's Colour Grid app generates 100 saturation and lightness levels for a chosen hue; a grid item click copies the hex code, and a text area at the end copies a color as a CSS custom property. As Refactoring UI notes, math alone can't craft the perfect palette, but it makes a useful starting point.
Measuring the lightness of an RGB color
This technique ignores the intrinsic value of a hue — the inherent brightness of a pure hue before any black or white is added, which is why pure yellow reads much brighter than pure purple. It measures how much white or black is mixed in, so judge the result by eye as well.
The measure is the average of the highest and lowest RGB values, divided by 255; the middle value plays no part. The result is a decimal from zero to one:
function getLightnessOfRGB(rgbString) {
// First convert to an array of integers by removing the whitespace, taking the 3rd char to the 2nd last then splitting by ','
const rgbIntArray = (rgbString.replace(/ /g, '').slice(4, -1).split(',').map(e => parseInt(e)));
// Get the highest and lowest out of red green and blue
const highest = Math.max(...rgbIntArray);
const lowest = Math.min(...rgbIntArray);
// Return the average divided by 255
return (highest + lowest) / 2 / 255;
}
Saturating an RGB color
Knowing the lightness lets us saturate without shifting lightness or hue. Two complications: a gray has no hue in RGB, so the function must handle that case, and a pure hue is only reachable at 50% lightness. This approach keeps the same lightness rather than moving toward 50%.
Take rgb(205, 228, 219), a light, muted cyan. Saturating means widening the gap between the lowest and highest value. To hold lightness steady, the highest value rises and the lowest falls by equal amounts; clamping at 0 and 255 limits how much change is possible, so each lightness has its own saturation range.
For a given color, the saturation range is the smaller of the distance from a same-lightness gray to 255 and the gray value itself. The gray is getLightnessOfRGB × 255, applied to all three channels:
// Using the previous "getLightnessOfRGB" function
const grayVal = getLightnessOfRGB('rgb(205, 228, 219)')*255; // 217
// So a gray version of our color would look like rgb(217,217,217);
// Now let's get the saturation range available:
const saturationRange = Math.round(Math.min(255-grayVal,grayVal)); // 38
Saturating by 50% means moving the extreme values by half the saturation range, clamped by the distance from the highest value to 255 and from the lowest value to 0:
// Get the maximum change by getting the minimum out of:
// (255 - the highest value) OR (the lowest value)
const maxChange = Math.min(255-228, 205); // 27
// Now we will be changing our values by the lowest out of:
// (the saturation range * the increase fraction) OR (the maximum change)
const changeAmount = Math.min(saturationRange/0.5, maxChange) // 19
Here that means adding 19 to green and subtracting 19 from the lowest channel:
const redResult = 205 - 19; // 186
const greenResult= 228 + 19; // 247
The middle value is found by ratio to gray. Compare its distance from the gray value with the distance of either extreme, and use that proportion to move it as the extremes move. The ratio calculation keeps the unrounded gray value for precision:
const grayVal = getLightnessOfRGB('rgb(205, 228, 219)')*255;
const highDiff = grayVal - 228; // -11 subtracting green - the highest value
const midDiff = grayVal - 219; // -2 subtracting blue - the middle value
const middleValueRatio = midDiff / highDiff; // 0.21739130434782608
Subtract the gray value from the new green value, multiply by the ratio, and add the result back to the gray:
// 247 is the green value after we applied the saturation transformation
const newBlue = Math.round(grayVal+(247-grayVal)*middleValueRatio); // 223
The resulting color is rgb(186, 247, 223) — more vibrant at the same lightness and hue. The function below saturates by 10%; it pairs with a helper that returns the RGB values sorted by size, used by every later function in the article. A gray input comes back unchanged:
function saturateByTenth(rgb) {
const rgbIntArray = (rgb.replace(/ /g, '').slice(4, -1).split(',').map(e => parseInt(e)));
const grayVal = getLightnessOfRGB(rgb)*255;
const [lowest,middle,highest] = getLowestMiddleHighest(rgbIntArray);
if(lowest.val===highest.val){return rgb;}
const saturationRange = Math.round(Math.min(255-grayVal,grayVal));
const maxChange = Math.min((255-highest.val),lowest.val);
const changeAmount = Math.min(saturationRange/10, maxChange);
const middleValueRatio =(grayVal-middle.val)/(grayVal-highest.val);
const returnArray=[];
returnArray[highest.index]= Math.round(highest.val+changeAmount);
returnArray[lowest.index]= Math.round(lowest.val-changeAmount);
returnArray[middle.index]= Math.round(grayVal+(returnArray[highest.index]-grayVal)*middleValueRatio);
return (`rgb(${[returnArray].join()})`);
}
function getLowestMiddleHighest(rgbIntArray) {
let highest = {val:-1,index:-1};
let lowest = {val:Infinity,index:-1};
rgbIntArray.map((val,index)=>{
if(val>highest.val){
highest = {val:val,index:index};
}
if(val<lowest.val){
lowest = {val:val,index:index};
}
});
if(lowest.index===highest.index){
lowest.index=highest.index+1;
}
let middle = {index: (3 - highest.index - lowest.index)};
middle.val = rgbIntArray[middle.index];
return [lowest,middle,highest];
}
Desaturating an RGB color
Fully desaturating yields a gray whose three channels equal the gray value. Partial desaturation reverses the saturating example. For the saturated rouge rgb(173, 31, 104), the lightness times 255 gives a gray of rgb(102, 102, 102):
const grayVal = Math.round(getLightnessOfRGB('rgb(173, 31, 104)') * 255); // 102
Find the saturation range again:
const saturationRange = Math.round(Math.min(255-grayVal,grayVal)); // 102
Then move the extremes 30% of that range toward gray, clamped by their equal distance from the gray value:
// Get the maximum change by getting the difference between the lowest (green) and the gray value
const maxChange = grayVal-31; // 71
// Now grab the value that represents 30% of our saturation range
const changeAmount = Math.min(saturationRange * 0.3, maxChange) // 30.59999
Add the change to the lowest value and subtract it from the highest:
const newGreen =Math.Round(31+changeAmount); // 62
const newRed =Math.Round(173-changeAmount); // 142
Apply the same ratio method for the third channel:
const highDiff = grayVal - 173; // -71 subtracting red - the highest value
const midDiff = grayVal - 104; // -2 subtracting blue - the middle value
const middleValueRatio = midDiff / highDiff; // 0.02816901408
const newBlue = Math.Round(grayVal+(142.4-grayVal)*middleValueRatio); // 103
The result, rgb(142, 62, 103), keeps its hue and lightness but is less vibrant. A desaturation function for 10% is the reverse of the saturation one:
function desaturateByTenth(rgb) {
const rgbIntArray = (rgb.replace(/ /g, '').slice(4, -1).split(',').map(e => parseInt(e)));
//grab the values in order of magnitude
//this uses the getLowestMiddleHighest function from the saturate section
const [lowest,middle,highest] = getLowestMiddleHighest(rgbIntArray);
const grayVal = getLightnessOfRGB(rgb) * 255;
if(lowest.val===highest.val){return rgb;}
const saturationRange = Math.round(Math.min(255-grayVal,grayVal));
const maxChange = grayVal-lowest.val;
const changeAmount = Math.min(saturationRange/10, maxChange);
const middleValueRatio =(grayVal-middle.val)/(grayVal-highest.val);
const returnArray=[];
returnArray[highest.index]= Math.round(highest.val-changeAmount);
returnArray[lowest.index]= Math.round(lowest.val+changeAmount);
returnArray[middle.index]= Math.round(grayVal+(returnArray[highest.index]-grayVal)*middleValueRatio);
return (`rgb(${[returnArray].join()})`);
}
Lightening while keeping hue
Lightening mixes in white: each channel rises by the same proportion of its distance to 255, so the color gradually loses saturation. For rgb(0, 153, 255), the distances to 255 are 255 (red), 102 (green) and zero (blue). Raising lightness by a tenth adds a tenth of 255 to the lowest value, with Math.min capping it at 255:
const red = 0;
const newRed = Math.round( red + Math.min( 255-red, 25.5 )); // 26
Red climbs from 0 to 26. The increase (26) divided by the original distance (255) gives the fraction the other channels must use:
const redDiff = 255 - red; // 255
const redIncrease = newRed - red; // 26
const increaseFraction = redIncrease / redDiff; // 0.10196
Multiply each remaining channel's distance to 255 by that fraction to get its addition:
const newGreen = Math.round(153 + (255 - 153) * increaseFraction); // 163
const newBlue = Math.round(255 + (255 - 255) * increaseFraction); // 255
The result, rgb(26, 163, 255), is the same hue, slightly lighter:
function lightenByTenth(rgb) {
const rgbIntArray = rgb.replace(/ /g, '').slice(4, -1).split(',').map(e => parseInt(e));
// Grab the values in order of magnitude
// This uses the getLowestMiddleHighest function from the saturate section
const [lowest,middle,highest]=getLowestMiddleHighest(rgbIntArray);
if(lowest.val===255){
return rgb;
}
const returnArray = [];
// First work out increase on lower value
returnArray[lowest.index]= Math.round(lowest.val+(Math.min(255-lowest.val,25.5)));
// Then apply to the middle and higher values
const increaseFraction = (returnArray[lowest.index]-lowest.val)/ (255-lowest.val);
returnArray[middle.index]= middle.val +(255-middle.val)*increaseFraction ;
returnArray[highest.index]= highest.val +(255-highest.val)*increaseFraction ;
// Convert the array back into an rgb string
return (`rgb(${returnArray.join()})`);
}
Darkening while keeping hue
Darkening is the reverse: reduce the highest value and take the fraction of that decrease, then move the other channels toward zero by their distance times that fraction. As with lightening, saturation is gradually lost along the way:
function darkenByTenth(rgb) {
// Our rgb to int array function again
const rgbIntArray = rgb.replace(/ /g, '').slice(4, -1).split(',').map(e => parseInt(e));
//grab the values in order of magnitude
//this uses the function from the saturate function
const [lowest,middle,highest]=getLowestMiddleHighest(rgbIntArray);
if(highest.val===0){
return rgb;
}
const returnArray = [];
returnArray[highest.index] = highest.val-(Math.min(highest.val,25.5));
const decreaseFraction =(highest.val-returnArray[highest.index])/ (highest.val);
returnArray[middle.index]= middle.val -middle.val*decreaseFraction;
returnArray[lowest.index]= lowest.val -lowest.val*decreaseFraction;
// Convert the array back into an rgb string
return (`rgb(${returnArray.join()}) `);
}
Choosing an approach
These building blocks cover rgb() work that won't go away, including legacy-browser requirements. For broader browser support, HSL and the conversion libraries above remain the lighter path; the Colour Grid tool handles quick conversions between hue variations.
Sponsor CSS-Tricks!
We've got lots of ways to help you connect with the greatest front-end community in all the land.



