CSS Color Module Level 6

Editor’s Draft,

More details about this document
This version:
https://drafts.csswg.org/css-color-5/
Latest published version:
https://www.w3.org/TR/css-color-5/
Feedback:
CSSWG Issues Repository
Inline In Spec
Editors:
Chris Lilley (W3C)
Una Kravets (Google)
Lea Verou (Invited Expert)
Adam Argyle (Google)
Suggest an Edit for this Spec:
GitHub Editor
Delta Spec:
yes
Not Ready For Implementation

This spec is not yet ready for implementation. It exists in this repository to record the ideas and promote discussion.

Before attempting to implement this spec, please contact the CSSWG at www-style@w3.org.


Abstract

This module extends CSS Color [css-color-5] to add contrast calculation.

CSS is a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, etc.

Status of this document

This is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

Please send feedback by filing issues in GitHub (preferred), including the spec code “css-color” in the title, like this: “[css-color] …summary of comment…”. All issues and comments are archived. Alternately, feedback can be sent to the (archived) public mailing list www-style@w3.org.

This document is governed by the 2 November 2021 W3C Process Document.

1. Introduction

This section is not normative.

This module adds a new <color> function: contrast-color().

2. Computing a Contrasting Color: the contrast-color() function

color_value/color-contrast

In only one current engine.

FirefoxNoneSafari🔰 15+ChromeNone
Opera?EdgeNone
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?

The contrast-color() functional notation identifies a sufficiently contrasting color against a specified background or foreground color without requiring manual computation.

Its syntax is:

<contrast-color()> = contrast-color(
  [ [ <color> && [ tbd-fg | tbd-bg ] && <target-contrast>? ] |
    [ <color> && [ tbd-fg | tbd-bg ] && <target-contrast>, <color># ] )
<target-contrast> = <wcag2>

The only mandatory argument is the base color against which the contrast is computed. This is typically (but not necessarily) a background color.

The optional list of <color> values represents the color candidates. If no candidates are provided, the default candidates are used: white, black.

The tbd-fg and tbd-bg keywords indicate the role of the base color in calculating the contrast: as text against a list of candidate background colors (text) or as a background against a list of candidate text colors. (The effective contrast of a pair of colors depends on their usage.)

The keywords to specify whether the base color is a foreground or background are TBD. [Issue #7359]

The <target-contrast> argument specifies the contrast algorithm(s) to use. If no color candidates have been provided, <target-contrast> may be omitted, in which case a UA-chosen algorithm is used.

Arguments to a <target-contrast> functional notation indicate the target contrast level. Multiple contrast algorithms with target contrast levels may be specified, in which case all their requirements are simultaneously applied. A contrast-color() function specifying multiple algorithms must specify a target contrast level for each algorithm, and is otherwise invalid.

If the target contrast level is omitted, the color candidate with the greatest contrast is returned. Otherwise, the returned color is the first color candidate that meets or exceeds that level, defaulting to white or black if none qualify.

2.1. Finding the Winning Color

2.1.1. If there is a target contrast

Candidate colors are tested sequentially, starting with the first color in the list, and ending with an automatically appended white, black. The first color to pass the specified level(s) of contrast against the base color wins.

If no candidate color passes, then whichever of white or black has the highest contrast according to the first specified algorithm wins. If they both have the same contrast, white wins.

contrast-color(wheat tbd-bg wcag2(aa), bisque, darkgoldenrod, olive, sienna, darkgreen, maroon)

The calculation is as follows:

The first color in the list which meets the desired contrast ratio of 4.5 is darkgreen.

contrast-color(wheat tbd-bg wcag2(5.8), bisque, darkgoldenrod, olive, sienna, darkgreen, maroon)

The calculation is as follows:

The first color in the list which meets the desired contrast ratio of 5.8 is maroon.

contrast-color(wheat tbd-bg wcag2(AA), bisque, darkgoldenrod, olive)

The calculation is as follows:

No color in the list meets the desired contrast ratio of 4.5. The contrast of white against the base color of wheat is 1.314, which is smaller than 4.5 (AA), and thus does not pass the target contrast. Therefore, black is returned, which has a contrast of 15.982 > 4.5.

2.1.2. If no target contrast is specified

Candidate colors are tested sequentially, starting with the first color in the list. A color is the temporary winner if it has the highest contrast against the base color of all those tested so far.

Once the end of the list is reached, the current temporary winner is the overall winner. Thus, if two colors in the list happen to have the same contrast, the earlier one wins.

--myAccent: #b22222;
color: contrast-color(wheat tbd-bg wcag2, tan, sienna, var(--myAccent), #d2691e)

The calculation is as follows:

The highest contrast ratio is 5.081 so var(--myAccent) wins

foo {
  --bg: hsl(200 50% 80%);
  --purple-in-hsl: hsl(300 100% 25%);
  color: contrast-color(var(--bg) tbd-fg wcag2, hsl(200 83% 23%), purple, var(--purple-in-hsl));
}

The calculation is as follows:

The calculated values here are shown to six significant figures, to demonstrate that early rounding to a lower precision would have given the wrong result (0.061575 is very close to 0.061487; 6.08409 is very close to 6.08889).

2.2. Contrast algorithms

Currently only WCAG 2.1 is supported, however this algorithm is known to have problems, particularly on dark backgrounds. Future revisions of this module will likely introduce additional contrast algorithms.

2.2.1. WCAG 2.1: the wcag2 keyword and wcag2() function

The wcag2 keyword and wcag2() functional notations indicate use of the [WCAG21] luminance contrast algorithm. Their syntax is:

<wcag2> =  wcag | wcag2([<number> | [ aa | aaa ] && large? ])

Its target contrast level keywords map as follows:

To find the contrast of a pair of colors, first their CIE Luminance (Y) is calculated relative to a D65 whitepoint. Then the WCAG 2.1 contrast is calculated: contrast = (Yl + 0.05) / (Yd + 0.05) where Yd is the luminance of the darker color in the pair and Yl is the luminance of the lighter color. The factor 0.05 represents the luminance contribution of the viewing flare.

Suppose that the base color were
color(display-p3 0.38 0.11 0.05)

while the first candidate color in the list were

yellow

The calculation is as follows:

2.2.2. Contrasting Semi-transparent Colors

This section applies only to contrast algorithms that require their inputs to be opaque colors.

When calculating the contrast of a pair of colors:

  1. The background color is first blended over an opaque canvas color using simple alpha compositing (see Compositing 1 § 5.1 Simple alpha compositing) to find an opaque background color.

    #7358 Find a good opaque canvas color for this computation. Candidates are:
    • the foreground color with alpha = 1

    • the canvas system color

    • some other color calculated to minimize the contrast for the algorithm used

  2. The foreground color is then blended over this opaque background color to find an opaque foreground color.

3. Resolving <color> Values

3.1. Resolving contrast-color() values

If all <color> parameters resolve to the corresponding colors in their respective color spaces, the computed value is the winning color resolved according to CSS Color 4 § 14 Resolving <color> Values. Otherwise (if currentColor was used in the function), the computed value is the contrast-color() function with each component computed value, thus preserving inheritance into child elements.

For example, given the value
contrast-color(rgb(179 213 230) tbd-bg wcag2(AA), cadetblue, hsl(200 83% 23%))

the contrast with cadetblue is 1.97 while the contrast with hsl(200 83% 23%) is 6.09 which exceeds 4.5, the value for AA; so it has the computed value of the resolved hsl function:

rgb(10 75 107)

For example, given a current color value of rgb(179 213 230), the value

contrast-color(currentColor tbd-bg wcag2(AA), hsl(200 83% 23%), purple)

has the computed value

contrast-color(currentColor tbd-bg wcag2(4.5), rgb(10 75 107), rgb(128 0 128))

4. Serialization

This section extends CSS Color 4 § 15 Serializing <color> Values to add serialization of the results of the contrast-color() function.

4.1. Serializing contrast-color()

The specified value of the contrast-color() function is serialized with each keyword value as specified and each component in canonical order.

The resolved value of the contrast-color() function is the used color serialized the same as any other <color>.

5. Security Considerations

No new security considerations have been reported on this specification.

6. Privacy Considerations

No new privacy considerations have been reported on this specification.

7. Accessibility Considerations

This specification introduces a new feature to help stylesheet authors write stylesheets which conform to WCAG 2.1 section 1.4.3 Contrast (Minimum).

8. Changes

8.1. Changes from Colors 5

The new contrast-color() function allows one of a list of colors to be chosen, based on the WCAG 2.1 contrast with a specified color.

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Advisements are normative sections styled to evoke special attention and are set apart from other normative text with <strong class="advisement">, like this: UAs MUST provide an accessible alternative.

Tests

Tests relating to the content of this specification may be documented in “Tests” blocks like this one. Any such block is non-normative.


Conformance classes

Conformance to this specification is defined for three conformance classes:

style sheet
A CSS style sheet.
renderer
A UA that interprets the semantics of a style sheet and renders documents that use them.
authoring tool
A UA that writes a style sheet.

A style sheet is conformant to this specification if all of its statements that use syntax defined in this module are valid according to the generic CSS grammar and the individual grammars of each feature defined in this module.

A renderer is conformant to this specification if, in addition to interpreting the style sheet as defined by the appropriate specifications, it supports all the features defined by this specification by parsing them correctly and rendering the document accordingly. However, the inability of a UA to correctly render a document due to limitations of the device does not make the UA non-conformant. (For example, a UA is not required to render color on a monochrome monitor.)

An authoring tool is conformant to this specification if it writes style sheets that are syntactically correct according to the generic CSS grammar and the individual grammars of each feature in this module, and meet all other conformance requirements of style sheets as described in this module.

Partial implementations

So that authors can exploit the forward-compatible parsing rules to assign fallback values, CSS renderers must treat as invalid (and ignore as appropriate) any at-rules, properties, property values, keywords, and other syntactic constructs for which they have no usable level of support. In particular, user agents must not selectively ignore unsupported component values and honor supported values in a single multi-value property declaration: if any value is considered invalid (as unsupported values must be), CSS requires that the entire declaration be ignored.

Implementations of Unstable and Proprietary Features

To avoid clashes with future stable CSS features, the CSSWG recommends following best practices for the implementation of unstable features and proprietary extensions to CSS.

Non-experimental implementations

Once a specification reaches the Candidate Recommendation stage, non-experimental implementations are possible, and implementors should release an unprefixed implementation of any CR-level feature they can demonstrate to be correctly implemented according to spec.

To establish and maintain the interoperability of CSS across implementations, the CSS Working Group requests that non-experimental CSS renderers submit an implementation report (and, if necessary, the testcases used for that implementation report) to the W3C before releasing an unprefixed implementation of any CSS features. Testcases submitted to W3C are subject to review and correction by the CSS Working Group.

Further information on submitting testcases and implementation reports can be found from on the CSS Working Group’s website at http://www.w3.org/Style/CSS/Test/. Questions should be directed to the public-css-testsuite@w3.org mailing list.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[COMPOSITING-1]
Rik Cabanier; Nikos Andronikos. Compositing and Blending Level 1. URL: https://drafts.fxtf.org/compositing-1/
[CSS-CASCADE-5]
Elika Etemad; Miriam Suzanne; Tab Atkins Jr.. CSS Cascading and Inheritance Level 5. URL: https://andreubotella.com/csswg-auto-build/test/css-cascade-5/
[CSS-COLOR-4]
Tab Atkins Jr.; Chris Lilley; Lea Verou. CSS Color Module Level 4. URL: https://andreubotella.com/csswg-auto-build/test/css-color/
[CSS-SYNTAX-3]
Tab Atkins Jr.; Simon Sapin. CSS Syntax Module Level 3. URL: https://andreubotella.com/csswg-auto-build/test/css-syntax/
[CSS-VALUES-4]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 4. URL: https://andreubotella.com/csswg-auto-build/test/css-values-4/
[CSSOM-1]
Daniel Glazman; Emilio Cobos Álvarez. CSS Object Model (CSSOM). URL: https://andreubotella.com/csswg-auto-build/test/cssom/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119
[WCAG21]
Andrew Kirkpatrick; et al. Web Content Accessibility Guidelines (WCAG) 2.1. URL: https://w3c.github.io/wcag/21/guidelines/

Informative References

[CSS-COLOR-5]
Chris Lilley; et al. CSS Color Module Level 5. URL: https://andreubotella.com/csswg-auto-build/test/css-color-5/

Issues Index

The keywords to specify whether the base color is a foreground or background are TBD. [Issue #7359]
Currently only WCAG 2.1 is supported, however this algorithm is known to have problems, particularly on dark backgrounds. Future revisions of this module will likely introduce additional contrast algorithms.
#7358 Find a good opaque canvas color for this computation. Candidates are: