Sub topic 14
Using HSL and HSV in CSS and code
This chapter turns the hue, saturation, and value ideas from earlier chapters into working code. It assumes you can read basic CSS and Python, and that you know the RGB, HSL, and HSV models from the previous chapters. By the end you should be able to write colors in HSL in CSS, convert between RGB, HSV, and HSL in Python, and avoid the usual mistakes.
Which model goes where
Browsers and design tools favor different models, so you will usually use each in a different place.
| Model | Where you meet it | Range of each channel | Typical use |
|---|---|---|---|
| HSL | CSS (`hsl()`), many design tool panels | H 0–360, S 0–100%, L 0–100% | Writing themes and palettes by hand |
| HSV (also called HSB) | Color pickers in image editors, Python's `colorsys` | H 0–360, S 0–100%, V 0–100% | Picking colors visually, programmatic adjustments |
| RGB | Everywhere underneath | 0–255 or 0–1 | What the screen finally displays |
Every HSL or HSV value is converted to RGB before it reaches the screen. The conversion is cheap and exact in both directions, apart from rounding.
HSL in CSS
CSS has no hsv() function. It does have hsl(), and that is the model you use for hue-based design in stylesheets.
.button {
background: hsl(210 80% 45%);
color: hsl(210 80% 98%);
border: 1px solid hsl(210 80% 30%);
}The hue is a number of degrees (an deg unit is optional). Saturation and lightness are percentages. The older comma form, hsl(210, 80%, 45%), still works. The space-separated form is the modern syntax and the one that allows an alpha channel after a slash:
.overlay {
background: hsl(210 80% 45% / 0.5);
}One hue, many colors with custom properties
The real advantage of HSL in CSS is that each channel has a meaning, so you can store the hue in a custom property and derive the rest. This is the technique from the topic's first example:
:root {
--brand-hue: 210;
--brand: hsl(var(--brand-hue) 80% 45%);
--brand-light: hsl(var(--brand-hue) 80% 85%);
--brand-dark: hsl(var(--brand-hue) 80% 20%);
--brand-muted: hsl(var(--brand-hue) 25% 45%);
--brand-complement: hsl(calc(var(--brand-hue) + 180) 80% 45%);
}Changing --brand-hue to 340 re-themes every derived color at once. Lightness changes make the light and dark variants. A lower saturation makes the muted tone. Adding 180 gives the complement.
Two details matter here:
- The custom property holds a bare number,
210, not210deg. A bare number works insidecalc()and insidehsl(). If you stored210deg,calc(var(--brand-hue) + 180)would mix an angle with a number and fail. - Hue wraps around.
hsl(390 80% 45%)is the same color ashsl(30 80% 45%), so the complement of a hue above 180 does not need a manual% 360.
Adjusting an existing color
Recent browsers support relative color syntax, which lets you take a color and change one channel:
.card {
--base: hsl(210 80% 45%);
background: hsl(from var(--base) h s calc(l + 40));
border-color: hsl(from var(--base) h calc(s - 40) l);
}Here h, s, and l stand for the channels of the source color. This also works when the source is a hex or rgb() color. Check browser support before relying on it, and keep a plain hsl() fallback declared earlier in the rule if you need older browsers.
HSV in code
Python's standard colorsys module converts between RGB, HSV, and HLS. All of its values are floats from 0 to 1, including hue. You multiply the hue by 360 to get degrees.
import colorsys
# A medium blue as RGB values between 0 and 1
r, g, b = 0.2, 0.4, 0.8
h, s, v = colorsys.rgb_to_hsv(r, g, b)
print(round(h * 360), round(s, 2), round(v, 2)) # 220 0.75 0.8
# Halve the saturation, keep hue and value
r2, g2, b2 = colorsys.hsv_to_rgb(h, s * 0.5, v)Halving saturation while holding hue and value fixed gives a more muted version of the same blue. The result is (0.5, 0.6, 0.8), give or take floating-point error.
Rotating hue
The complement is a half turn around the wheel. In colorsys units that is 0.5, and the modulo keeps the result in range:
import colorsys
def complement(r, g, b):
h, s, v = colorsys.rgb_to_hsv(r, g, b)
return colorsys.hsv_to_rgb((h + 0.5) % 1.0, s, v)
print(complement(1.0, 0.5, 0.0)) # orange gives a blue-leaning colorThe same pattern gives other harmonies. For triadic colors, rotate by 1/3 and 2/3. For analogous colors, rotate by small steps such as 1/12 (30 degrees).
The HLS ordering trap
colorsys has no function named rgb_to_hsl. It offers rgb_to_hls and hls_to_rgb, and the channel order is hue, lightness, saturation, not hue, saturation, lightness. Passing arguments in CSS order produces a wrong color with no error, because every value is a valid float between 0 and 1.
The helper below hides the mix-up. It takes degrees and percentages as fractions, in CSS order, and returns a hex string:
import colorsys
def hsl_to_hex(h, s, l):
"""h in degrees, s and l as fractions from 0 to 1."""
r, g, b = colorsys.hls_to_rgb((h % 360) / 360, l, s) # note the l, s order
return "#{:02x}{:02x}{:02x}".format(
round(r * 255), round(g * 255), round(b * 255)
)
print(hsl_to_hex(210, 0.80, 0.45)) # #1773cfPutting it together: a generated ramp
A common job is producing a lightness ramp for one hue, the code version of tints and shades. This script prints a ramp as CSS custom properties:
import colorsys
def hsl_to_hex(h, s, l):
r, g, b = colorsys.hls_to_rgb((h % 360) / 360, l, s)
return "#{:02x}{:02x}{:02x}".format(
round(r * 255), round(g * 255), round(b * 255)
)
def ramp(hue, saturation, lightness_steps):
for i, l in enumerate(lightness_steps, start=1):
yield f"--brand-{i * 100}: {hsl_to_hex(hue, saturation, l)};"
steps = [0.95, 0.85, 0.70, 0.55, 0.45, 0.30, 0.20]
for line in ramp(210, 0.80, steps):
print(line)The hue and saturation stay fixed while lightness moves, so every swatch belongs to the same family. The diagram shows the path a color takes in code.
Edge cases and common errors
Hue is undefined for grays. When saturation is 0, every hue gives the same color. colorsys.rgb_to_hsv(0.5, 0.5, 0.5) returns a hue of 0.0, which does not mean red. If you rotate the hue of a gray, nothing changes, and that is correct. If you raise the saturation of a gray afterward, it will turn red because the stored hue is 0. Keep the intended hue separately if you need it.
Hue ranges differ between tools. CSS uses degrees from 0 to 360, colorsys uses 0 to 1, and some libraries use 0 to 255. Convert at the boundary and name variables clearly, for example hue_deg and hue_unit.
Out-of-range values. Adding 40 to a lightness of 70% gives 110%. CSS clamps this to white and colorsys may return values above 1. Clamp before scaling to bytes:
def clamp(x, low=0.0, high=1.0):
return max(low, min(high, x))HSL and HSV values are not interchangeable. hsl(210 80% 45%) and an HSV value of 210, 80%, 45% are different colors. In HSV, 100% value with full saturation gives the purest color. In HSL, the purest color sits at 50% lightness, and 100% lightness is always white. When you copy numbers from a picker, check which model it uses.
Rounding drifts. Converting RGB to HSL and back with rounded integers can change a channel by one step. Store the original hex as the source of truth, and convert only when you need to adjust.
Numeric lightness is not perceived lightness. hsl(60 100% 50%) (yellow) and hsl(240 100% 50%) (blue) have the same L but look very different in brightness. Equal steps in L do not make a visually even ramp, and they do not guarantee readable text. Check contrast ratios separately, as covered in the chapter on accessibility.
Choosing between HSL and HSV
Use HSL in stylesheets because it is the model CSS supports, and its lightness axis maps neatly to "lighter" and "darker" variants. Use HSV when you want to mimic a picker, where the top-right corner is the most vivid color, or when you are scaling brightness without washing out toward white. For either model, treat the numbers as a convenient way to make deliberate changes, and judge the result by eye and by contrast ratio.
Exercise
A stylesheet defines --accent-hue: 300; and --accent-complement: hsl(calc(var(--accent-hue) + 180) 70% 50%);. The complement renders correctly even though 300 + 180 = 480, which is above 360. Why does it work? Then name the mistake in this Python line meant to build the same color: colorsys.hls_to_rgb(300/360, 0.7, 0.5).
Show answer
CSS hue wraps around the color wheel, so 480 is treated as 480 − 360 = 120, a green, which is the correct complement of magenta at 300. In the Python line, the arguments are in the wrong order. hls_to_rgb expects hue, lightness, saturation, so saturation 0.7 and lightness 0.5 should be passed as (300/360, 0.5, 0.7). As written, the call uses lightness 0.7 and saturation 0.5, which gives a different, lighter color. The call also does not rotate the hue by 180 degrees, so it needs ((300 + 180) % 360) / 360 for the hue.
Exercise
You convert the gray (0.5, 0.5, 0.5) to HSV, set the saturation to 0.6, and convert back. The result is a dull red instead of a gray with a tint. What caused it, and how do you fix it?
Show answer
A gray has saturation 0, so its hue is undefined and colorsys reports 0.0, which is red. Raising the saturation applies that placeholder hue. To fix it, choose the hue you want explicitly, for example h = 210/360, and use that value instead of the one returned by the conversion.