How to Convert HEX to HWB
Converting a hexadecimal color code to HWB (Hue, Whiteness, Blackness) bridges the gap between how computers render color and how humans naturally mix it. While HEX is perfect for a machine reading RGB light values, HWB is designed to mimic the way a painter mixes pigments on a palette.
Understanding HWB
HWB was created by the same person who invented HSL, but it takes a slightly different approach to color manipulation:
- Hue (0° - 360°): The base color on the color wheel. For example,
0°is red,120°is green, and240°is blue. - Whiteness (0% - 100%): How much white paint you are mixing into the base hue. Adding white creates a tint.
- Blackness (0% - 100%): How much black paint you are mixing in. Adding black creates a shade.
If you mix 100% white and 100% black together, you just get gray. In CSS, if your Whiteness and Blackness values add up to 100% or more, the hue is completely washed out, resulting in a shade of gray.
Why Use HWB Over HEX?
HWB is incredibly useful for building monochromatic color palettes. If your brand's primary color is a specific blue, you can lock in the Hue and simply adjust the Whiteness to create background tints, or increase the Blackness to create dark text shades.
Doing this in HEX requires complex math or a visual color picker. In HWB, creating a lighter version of a color is as simple as typing a higher Whiteness percentage.
The Conversion Process
To get from HEX to HWB, the color must first be decoded into standard RGB values. From there, the math calculates the Hue (identical to how it's calculated for HSL). The Whiteness is simply the lowest of the three RGB channels, while the Blackness is calculated by subtracting the highest RGB channel from 100%.
Converting HEX to HWB in JavaScript
If you are building a design tool or theme generator, here is how you can programmatically convert a 6-character HEX code into HWB:
function hexToHwb(hex) {
// 1. Convert HEX to RGB (0-1 scale)
let r = parseInt(hex.substring(1, 3), 16) / 255;
let g = parseInt(hex.substring(3, 5), 16) / 255;
let b = parseInt(hex.substring(5, 7), 16) / 255;
let max = Math.max(r, g, b);
let min = Math.min(r, g, b);
// 2. Calculate Whiteness and Blackness
let w = min;
let bk = 1 - max;
let h = 0;
// 3. Calculate Hue
if (max !== min) {
let d = max - min;
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return {
h: Math.round(h * 360),
w: Math.round(w * 100),
b: Math.round(bk * 100)
};
}