CSS Color Module Level 5

Editor’s Draft,

Specification Metadata
This version:
https://drafts.csswg.org/css-color-5/
Latest published version:
https://www.w3.org/TR/css-color-5/
Previous Versions:
Issue Tracking:
CSSWG Issues Repository
Inline In Spec
Editors:
(W3C)
Una Kravets (Google)
Lea Verou (Invited Expert)
Adam Argyle (Google)
Suggest an Edit for this Spec:
GitHub Editor
Delta Spec:
yes

Abstract

This module extends CSS Color [css-color-4] to add color modification functions.

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 15 September 2020 W3C Process Document.

1. Introduction

This section is not normative.

Web developers, design tools and design system developers often use color functions to assist in scaling the design of their component color relations. With the increasing usage of design systems that support multiple platforms and multiple user preferences, like the increased capability of Dark Mode in UI, this becomes even more useful to not need to manually set color, and to instead have a single source from which schemes are calculated.

LC color picker
chloropleth map of the US

Above, a color picker operating in LCH space. Here, a pair of colors are being used to define a color scale on the Chroma-Lightness plane (constant Hue). Below, the color scale in use on a chloropleth map.

Currently Sass, calc() on HSL values, or PostCSS is used to do this. However, preprocessors are unable to work on dynamically adjusted colors; all current solutions are restricted to the sRGB gamut and to the perceptual limitations of HSL (colors are bunched up in the color wheel, and two colors with visually different lightness, like yellow and blue, can have the same HSL lightness).

This module adds three functions: color-mix(), color-contrast(), and a way to modify colors.

The perceptually uniform ``lch()`` color space is used for mixing by default, as this has no gamut restrictions and colors are evenly distributed. However, other color spaces can be specified, including ``hsl()`` or ``srgb`` if desired.

2. color spaces {#color spaces-section}

Mixing or otherwise combining colors has different results depending on the color space used. In some cases, the result of physically mixing two colored lights is desired (in that case, the CIE XYZ color space is appropriate, because it is linear in light intensity). In other cases, colors which are evenly spaced perceptually are desired (in which case, the CIE Lab color space is designed to be perceptually uniform). Alternatively, maximizing chroma so that color mixtures follow along the hue wheel is wanted (CIE LCH works well for this). Lastly, compatibility with legacy Web content may be the most important consideration. (the sRGB color space, which is neither linear-light nor perceptually uniform, is the choice here).

<color space> = srgb | hsl | hwb | xyz | lab | lch

When no color space is specified, the mixing is done in the lch color space. The xyz color space is CIE XYZ, with a D50 whitepoint, and allows computation to be done in a linear-light-intensity space.

3. Mixing colors: the color-mix() function

This function takes two <color> specifications and returns the result of mixing them, in a given color space, by a specified amount.

color-mix() = color-mix( in <<color space>> , [ <color> && <percentage>? ]#{2})

The percentages are normalized as follows:

  1. Let p1 be the first percentage and p2 the second one.

  2. If both percentages are omitted, they each default to 50% (an equal mix of the two colors).

  3. Otherwise, if p2 is omitted, it becomes 100% - p1

  4. Otherwise, if p1 is omitted, it becomes 100% - p2

  5. If the percentages sum to zero do something, tbd

  6. Otherwise, if both are provided but do not add up to 100%, they are scaled accordingly so that they add up to 100%.

This means that p1 becomes p1 / (p1 + p2) and p2 becomes p2 / (p1 + p2).

Should we handle p1 + p2 < 100% differently? E.g. a mix with `transparent`?

After normalizing both percentages, the result is produced via the following algorithm:

  1. Both colors are converted to the specified color space. If the specified color space has a smaller gamut than the one in which the color to be adjusted is specified, gamut mapping will occur.

  2. Colors are then interpolated in the specified color space.

The result of mixing is the color at the specified percentage along the progression of the second color to the first color.

Note: As a corrollary, a percentage of 0% just returns the other color converted to the specified color space, and a percentage of 100% returns the same color converted to the specified color space.

This example produces a mixture of 40% peru and 60% palegoldenrod.
color-mix(in lch, peru 40%, palegoldenrod)

The mixing is done in lch() color space. Here is a top-down view, looking along the neutral L axis:

Mixtures of peru and palegoldenrod. Peru has a hue angle, measured from the positive a axis, of 63.677 degrees while palegoldenrod has a hue angle of 98.834 degrees. Peru has a chroma, or distance from the central neutral axis, of 54.011 while palegoldenrod has a chroma of 31.406. Mixtures lie along the curve. A 40%/60% mixture is shown.

The calculation is as follows:

This example produces the mixture of teal and olive, in lch color space (the default), with each lch channel being 65% of the value for teal and 35% of the value for olive.

Note: interpolating on hue and chroma keeps the intermediate colors as saturated as the endpoint colors.

color-mix(in lch, teal 65%, olive);
Mixtures of teal and olive. Teal has a hue angle, measured from the positive a axis, of 196.4524 degrees while olive has a hue angle of 99.5746 degrees. Teal has a chroma, or distance from the central neutral axis, of 31.6903 while olive has a chroma of 56.8124. Mixtures lie along the dashed curve. A 65%/35% mixture is shown.

The calculation is as follows:

4. Selecting the most contrasting color: the color-contrast() function

This function takes, firstly, a single color (typically a background, but not necessarily), secondly, a list of two or more colors, and thirdly, an optional target luminance contrast [WCAG21]. It selects from that list the first color color to meet or exceed the target contrast. If no target is specified, it selects the first color with the highest contrast to the single color.

The single color is separated from the list with the keyword vs and the target contrast, if present, is separated from the list with the keyword to.

color-contrast() = color-contrast( <color> vs <color>#{2,}  [ to [<number> | AA | AA-large]]? )

The keyword AA is equivalent to 4.5, and the keyword AA-large is equivalent to 3.

color-contrast(wheat vs tan, sienna, var(--myAccent), #d2691e)

The calculation is as follows:

Suppose myAccent has the value #b22222:

The highest contrast ratio is 5.081 so var(--myAccent) wins
color-contrast(wheat vs bisque, darkgoldenrod, olive, sienna, darkgreen, maroon to AA)

The calculation is as follows:

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

color-contrast(wheat vs bisque, darkgoldenrod, olive, sienna, darkgreen, maroon to 5.8)

The calculation is as follows:

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

The colors in the list (after the keyword vs) are tested sequentially, from left to right; a color is the temporary winner if it has the highest contrast of all those tested so far.

List traversal is terminated once the target contrast has been met or exceeded.

Once the end of the list is reached, if there is no target contrast, the current temporary winner is the overall winner. Thus, if two colors in the list happen to have the same contrast, the earlier in the list wins because the later one has the same contrast, not higher.

If there is a target contrast, and the end of the list is reached without meeting that target, either white or black is returned, whichever has the higher contrast.

color-contrast(wheat vs bisque, darkgoldenrod, olive to AA)

The calculation is as follows:

No color in the list meets the desired contrast ratio of 4.5, so black is returned as the contrast (15.982) is higher than that of white (1.314).

foo {
  --bg: hsl(200 50% 80%);
  --purple-in-hsl: hsl(300 100% 25%);
  color: color-contrast(var(--bg) vs 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).

5. Modifying colors

Note: There are currently two proposals for modifying colors: color-adjust and Relative color syntax.

there are two proposals for color modification (proposal 1, proposal 2). The CSS WG expects that the best aspects of each will be chosen to produce a single eventual solution. <https://github.com/w3c/csswg-drafts/issues/3187>

5.1. Adjusting colors: the color-adjust function

This function takes one <color> specification and returns the result of adjusting that color, in a given color space, by a specified color-adjuster.

Unless otherwise specified, the adjustment is done in the lch color space.

Multiple color functions can be specified.

color-adjust() = color-adjust( <color> [ <color-adjuster> && [ in <<color space>> ]? ]? )
<color-adjuster> = [ [
      <srgb-adjuster> | <hsl-adjuster> | <hwb-adjuster>
    | <xyz-adjuster> | <lab-adjuster> | <lch-adjuster>
  ] | alpha ] <percentage>?
<srgb-adjuster> = red | green | blue
<hsl-adjuster> = <hue-adjuster> | saturation | lightness
<hwb-adjuster> = <hue-adjuster> |  whiteness | blackness
<xyz-adjuster> = x | y | z
<lab-adjuster> = lightness | a | b
<lch-adjuster> = lightness | chroma | <hue-adjuster>
<hue-adjuster> = hue [shorter | longer | increasing | decreasing | specified ]?

The meaning of the adjusters is defined by color space. For example, if the color space is hsl, hue means the HSL hue, which is not the same as the LCH hue; if the color space is lch, lightness means the LCH Lightness, which is the same as Lab lightness, but different to the HSL Lightness.

Only the color-adjusters defined for a given color space are available. For example, it is not possible to use the HWB whiteness adjuster unless the color space is hwb. The alpha adjuster is available on any color space.

Note: not all color-adjusters are equally useful. Adjustments in LCH are the most useful, which is why it is the default. Adjustments on the a and b axes are rarely needed. Adjustments in the srgb-related spaces (srgb itself, hsl, hwb) are provided mainly for backward compatibility with the sorts of adjustments currently done in CSS preprocessors. Adjusting the individual x, y and z channels will produce significant hue shifts; however, adjusting all three channels together is useful and will lighten or darken the color.

The hue-adjuster takes optional keywords, to specify the CSS Color 4 §13.3 Hue interpolation algorithm. If no keyword is specified, it is as if shorter were specified.

This example produces the adjustment of peru (#CD853F), in lch() color space (the default), with the lightness being reduced by 20%. The chroma and hue of red are left unchanged.
color-adjust(peru lightness -20%);

The calculation is as follows:

5.2. Relative color syntax

In previous levels of this specification, the color functions could only specify colors in an absolute manner, by directly specifying all of the color channels.

The new relative color syntax allows existing colors to be modified using the color functions: if an origin color is specified, then each color channel can either be directly specified, or taken from the origin color (and possibly modified with math functions).

A future version of this specification may define a relative syntax for color() as well.

The precise details of each function’s changes to accomodate relative colors are listed below, but they all follow a common structure:

If the origin color was originally specified with a different color function, it’s first converted into the chosen color function, so it has meaningful values for the channels.

For example, if a theme color is specified as opaque, but in a particular instance you need it to be partially transparent:
html { --bg-color: blue; }
.overlay {
  background: rgb(from var(--bg-color) r g b / 80%);
}

In this example, the r, g, and b channels of the origin color are unchanged, indicated by specifying them with the keywords drawing their values from the origin color, but the opacity is set to 80% to make it slightly transparent, regardless of what the origin color’s opacity was.

By using the channel keywords in a math function, an origin color can be manipulated in more advanced ways.
html { --color: green; }
.foo {
  --darker-accent: lch(from var(--color) calc(l / 2) c h);
}

In this example, the origin color is darkened by cutting its lightness in half, without changing any other aspect of the color.

Note as well that the origin color is a color keyword (effectively RGB), but it’s automatically interpreted as an LCH color due to being used in the lch() function.

While most uses of relative color syntax will use the channel keywords in their corresponding argument, you can use them in any position.

For example, to do a rough approximation of grayscaling a color:

--blue-into-gray: rgb(from var(--color)
                    calc(r * .3 + g * .59 + b * .11)
                    calc(r * .3 + g * .59 + b * .11)
                    calc(r * .3 + g * .59 + b * .11));

Using this, red would become rgb(30% 30% 30%), green would become rgb(59% 59% 59%), and blue would become rgb(11% 11% 11%). A more moderate color, like darkolivegreen, which has RGB values rgb(85 107 47), would become approximately rgb(37% 37% 37%).

(Note, tho, that an easier and more accurate way to grayscale a color is to use the lch() function, as that color space is more accurate to human perception: lch(from var(--color) l 0 h) preserves the lightness, but zeroes out the chroma, which determines how "colorful" the color is.)

5.2.1. Relative RGB colors

The grammar of the rgb() function is extended as follows:

rgb() = rgb( <percentage>{3} [ / <alpha-value> ]? ) |
        rgb( <number>{3} [ / <alpha-value> ]? ) |
        rgb( [ from <color> ]? [ <number> | <percentage> ]{3} [ / <alpha-value> ]? )

Within a relative color syntax rgb() function, the allowed channel keywords are:

To manipulate color channels in the sRGB color space:
rgb(from  indianred 255 g b)

This takes the sRGB value of indianred (205 92 92) and replaces the red channel with 255 to give rgb(255 92 92).

5.2.2. Relative HSL colors

The grammar of the hsl() function is extended as follows:

hsl() = hsl([from <color>]? <hue> <percentage> <percentage> [ / <alpha-value> ]? )

Within a relative color syntax hsl() function, the allowed channel keywords are:

This adds 180 degrees to the hue angle, giving a complementary color.
--accent:  lightseagreen;
--complement:   hsl(from var(--accent) calc(h + 180deg) s l);

lightseagreen is hsl(177deg 70% 41%), so --complement is hsl(357deg 70% 41%)

5.2.3. Relative HWB colors

The grammar of the hwb() function is extended as follows:

hwb() = hwb([from <color>]? <hue> <percentage> <percentage> [ / <alpha-value> ]? )

Within a relative color syntax hwb() function, the allowed channel keywords are:

5.2.4. Relative Lab colors

The grammar of the lab() function is extended as follows:

lab() = lab([from <color>]? <percentage> <number> <number> [ / <alpha-value> ]? )

Within a relative color syntax lab() function, the allowed channel keywords are:

Multiple ways to adjust the transparency of a base color:

Note that all the adjustments are lossless in the sense that no gamut clipping occurs, since lab() encompasses all visible color. This is not true for the alpha adjustments in the sRGB based functions (such as 'rgb()', 'hsl()', or 'hwb()'), which would also convert to sRGB in addition to adjusting the alpha transparency.

Fully desaturating a color to gray, keeping the exact same lightness:
--mycolor:  orchid;
// orchid is lab(62.753% 52.460 -34.103)
--mygray:  lab(from var(--mycolor) l 0 0)
// mygray is lab(62.753% 0 0) which is rgb(59.515% 59.515% 59.515%)

5.2.5. Relative LCH colors

The grammar of the lch() function is extended as follows:

lch() = lch([from <color>]? <percentage> <number> <hue> [ / <alpha-value> ]? )

Within a relative color syntax lch() function, the allowed channel keywords are:

lch(from peru calc(l * 0.8) c h) produces a color that is 20% darker than peru or lch(62.2532% 54.0114 63.6769), with its chroma and hue left unchanged. The result is lch(49.80256% 54.0114 63.6769)
This adds 180 degrees to the hue angle, giving the complementary color.
--accent:  lightseagreen;
--complement:   LCH(from var(--accent) l c calc(h + 180deg));

lightseagreen is LCH(65.4937% 39.4484 190.1013), so --complement is LCH(65.4937% 39.4484 370.1013)

Fully desaturating a color to gray, keeping the exact same lightness:
--mycolor:  orchid;
// orchid is lch(62.753% 62.571 326.973)
--mygray:  lch(from var(--mycolor) l 0 h)
// mygray is lch(62.753% 0 326.973) which is rgb(59.515% 59.515% 59.515%)

But now (since the hue was preserved) re-saturating again

--mymuted:  lch(from var(--mygray) l 30 h);
// mymuted is lch(62.753% 30 326.973) which is rgb(72.710% 53.293% 71.224%)

6. Security and Privacy Considerations

No new security or 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. Since the FPWD of 10 June 2020

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.

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

[CSS-COLOR-3]
Tantek Çelik; Chris Lilley; David Baron. CSS Color Module Level 3. 19 June 2018. REC. URL: https://www.w3.org/TR/css-color-3/
[CSS-COLOR-4]
Tab Atkins Jr.; Chris Lilley. CSS Color Module Level 4. 12 November 2020. WD. URL: https://www.w3.org/TR/css-color-4/
[CSS-VALUES-3]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 3. 6 June 2019. CR. URL: https://www.w3.org/TR/css-values-3/
[CSS-VALUES-4]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 4. 11 November 2020. WD. URL: https://www.w3.org/TR/css-values-4/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[WCAG21]
Andrew Kirkpatrick; et al. Web Content Accessibility Guidelines (WCAG) 2.1. 5 June 2018. REC. URL: https://www.w3.org/TR/WCAG21/

Issues Index

Should we handle p1 + p2 < 100% differently? E.g. a mix with `transparent`?
there are two proposals for color modification (proposal 1, proposal 2). The CSS WG expects that the best aspects of each will be chosen to produce a single eventual solution. <https://github.com/w3c/csswg-drafts/issues/3187>
A future version of this specification may define a relative syntax for color() as well.