Andrew's Digital Garden

contrast-color()

contrast-color() takes a colour value and returns a contrasting colour. This can be used to ensure WCAG AA [[a11y]] compliance. The returned value is always white or black.

The exact method of finding this colour is up to the browser.

button { background-color: var(--button-color); color: contrast-color(var(--button-color)); }

Using [[20250729123817-css-relative-colors]], you can get pretty programmatic components that use just a single colour.

Remember that you can likely create a background colour that doesn't work with white or black text, so some care is still required.

Warning: WCAG AA (4.5:1) contrast is not capable of producing clearly readable text in all cases. Mid-tone background colors generally don't provide enough contrast with either black or white foreground. For example, contrast-color() on a royal bluish (#2277d3) background produces black text, which is not readable for small text. It is recommended, therefore, to use light or dark colors with the contrast-color() function.

This used to be the color-contrast function, but was renamed

[[css]]

contrast-color()