Skip to contents

Calculates the WCAG 2 contrast ratio between each colour in a palette and a single comparison colour, for example to check whether text in that colour would be readable on each colour in the palette.

Usage

contrast_ratio(colour, against = "white", ...)

Arguments

colour

The colours to check. Either a vector of recognised colour names and/or hex colour codes (e.g. c("white", "#0F4B63")), such as the output of generate_palette(), or a single vector of length 3 (red value, green value, blue value, e.g. c(15, 75, 99)), with all values between 0 and 255.

against

The colour to compare against. Defaults to white. Must be a single recognised colour name (e.g. "black"), hex colour code (e.g. "#000000") or vector of length 3 (red value, green value, blue value), with all values between 0 and 255.

...

color, the US spelling of colour. Other argument names give an error.

Value

A numeric vector of contrast ratios, one per colour in colour, between 1 (no contrast) and 21 (black vs white). Names of colour are kept.

Details

WCAG guidance recommends a contrast ratio of at least 4.5:1 for normal text (3:1 for large text) to meet level AA, and at least 7:1 (4.5:1 for large text) to meet level AAA. Values are returned unrounded; if you round them before comparing with these thresholds, round down.

Examples

contrast_ratio("#767676")
#> [1] 4.542225

contrast_ratio(
  c("unripe" = "#89973d", "ripe" = "#e8b92f", "overripe" = "#a45e41"),
  against = "black"
)
#>    unripe      ripe  overripe 
#>  6.557701 11.411793  4.255915 

contrast_ratio(generate_palette("steelblue", "go_both_ways", n_colours = 5))
#> [1]  1.268264  2.177296  4.107557  8.732732 17.618851

contrast_ratio(c(15, 75, 99), against = c(255, 255, 255))
#> [1] 9.515554