5.18 Measure color contrast

The themes provide the functions modus-themes-wcag-formula and modus-themes-contrast. The former is a direct implementation of the WCAG formula: https://www.w3.org/TR/WCAG20-TECHS/G18.html. It calculates the relative luminance of a color value that is expressed in hexadecimal RGB notation. While the latter function is just a convenient wrapper for comparing the relative luminance between two colors.

In practice, one needs to work only with modus-themes-contrast. It accepts two color values and returns their contrast ratio. Values range from 1 to 21 (lowest to highest). The themes are designed to always be equal or higher than 7 for each combination of background and foreground that they use (this is the WCAG AAA standard—the most demanding of its kind).

A couple of examples (rounded numbers):

;; Pure white with pure green
(modus-themes-contrast "#ffffff" "#00ff00")
;; => 1.37
;; That is an outright inaccessible combo

;; Pure black with pure green
(modus-themes-contrast "#000000" "#00ff00")
;; => 15.3
;; That is a highly accessible combo

It does not matter which color value comes first. The ratio is always the same.

If one does not wish to read all the decimal points, it is possible to try something like this:

(format "%0.2f" (modus-themes-contrast "#000000" "#00ff00"))

While it is fine to perform such calculations on a case-by-case basis, it is preferable to implement formulas and tables for more demanding tasks. Such instruments are provided by org-mode or orgtbl-mode, both of which are built into Emacs. Below is such a table that derives the contrast ratio of all colors in the first column (pure red, green, blue) relative to the color specified in the first row of the second column (pure white) and rounds the results:

|         | #ffffff |
|---------+---------|
| #ff0000 |    4.00 |
| #00ff00 |    1.37 |
| #0000ff |    8.59 |
#+tblfm: $2='(modus-themes-contrast $1 @1$2);%0.2f

To measure color contrast one needs to start from a known value. This typically is the background. The Modus themes define an expanded palette in large part because certain colors are only meant to be used in combination with some others. Consult the source code for the minutia and relevant commentary.

Such knowledge may prove valuable while attempting to override some of the themes’ colors: Override colors.