Color, contrast, and forced colors
Make web components readable for everyone: WCAG contrast ratios, color blindness, forced colors mode with system colors, and forced-color-adjust.
- 01Measure contrast the way WCAG doesCheck text against 4.5:1 or, when it's large, 3:1, and a control's parts against 3:1, using the colors Chrome computes.
- 02Never let color work aloneSee your component through Chrome's color vision filters, and give every color a second cue, like a word.
- 03Support forced colors modeBring back what the browser wipes out with
@media (forced-colors: active)and system colors, and opt out only for swatches.
How do you make a web component readable for everyone?
Ravi has given Leaf and Kettle's menu some color. Each tea gets a badge: green for green tea, brown for oolong, and black for black tea. There's a new switch too, Add milk. Then three regulars visit.
- Suresh has low vision. Pale, thin text blurs for him.
- Arun sees red poorly. To him, the green badge and the brown one look the same.
- Farah uses a Windows contrast theme: white text on black, everywhere. On Ravi's menu, the switch has vanished.
One page, three problems. How does one component work for all three people?
Give text 4.5:1 contrast with its background, or 3:1 when it's large, and give the parts of a control 3:1. Never let color carry meaning alone: add a word, an icon, or a shape. And let forced colors mode win: in the component's own sheet, use @media (forced-colors: active) and system colors like CanvasText to bring back what the browser wiped out.
Here is Ravi's menu, with the kit as lesson 14.5 left it:
<link rel="stylesheet" href="tea-kit/tokens.css"><p>Green badge: green tea. Brown: oolong. Black: black tea.</p><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><p>Tie Guan Yin <tea-badge kind="oolong">Organic</tea-badge></p><p>Assam <tea-badge kind="black">Strong</tea-badge></p><tea-toggle>Add milk</tea-toggle><script type="module"> import "./tea-kit/index.js";</script>- Line 1 links the kit's tokens, the colors every component shares, from lesson 12.6.
- Line 2 is the legend. It says what each badge color means.
- Lines 3 to 5 are three teas. Each badge's
kindattribute picks its color. - Line 6 is the switch from lesson 13.2.
If you see colors the way Ravi does, the badges are easy to tell apart. This lesson checks the menu the way each regular sees it. Then it fixes the kit.
A stop sign is red. It's also eight-sided, and it says STOP in big white letters. A driver who can't see red still knows it by its shape and its word. At night, the headlights wash out the red, but the white letters and the edge still show.
- In real life: Big white letters on red
- In JavaScript: Text with enough contrast: 4.5:1, or 3:1 when large
- In real life: The eight-sided shape and the word STOP
- In JavaScript: A second cue, so color isn't the only clue
- In real life: Headlights at night that wash out the red
- In JavaScript: Forced colors mode, which replaces your colors
Measure every pair of colors, never let color work alone, and let the person's colors win. Text needs 4.5:1, large text and control parts 3:1. Each color needs a second cue. In forced colors mode, bring back missing parts with system colors.
What contrast ratio does text need?
Suresh reads the menu with his nose close to the screen. What he needs is contrast: a big gap in lightness between the text and what's behind it.
A contrast ratio measures that gap. It runs from 1:1, the same color twice, to 21:1, black on white. Lesson 14.1 turned WCAG's formula into JavaScript. This lesson reuses it as the contrast.js tab. Its ratio(a, b) takes two colors and returns the ratio, like 4.24:1.
WCAG is the Web Content Accessibility Guidelines. Its rule 1.4.3, Contrast (Minimum), asks for two things:
- 4.5:1 between text and its background.
- 3:1 for large text.
What counts as large? WCAG says 18 points, or 14 points when the text is bold. CSS has 4 pixels for every 3 points. So large text is 24px, or about 18.7px when bold. Bigger, thicker letters are easier to read, so they get a lower line.
One more rule: never round. The 1.4.3 page says 4.499:1 doesn't meet 4.5:1. That's why contrast.js cuts the number to two places. MDN's guide has the same lines in a short table.
A café writes TODAY'S SPECIALS in huge letters across its chalkboard, in yellow chalk. The prices sit underneath in small print, in thick white chalk. The huge letters can be a little paler and still be read from the door. The small print needs the strongest chalk there is.
- In real life: The big headline, in yellow chalk
- In JavaScript: Large text, which needs 3:1
- In real life: The small prices, in thick white chalk
- In JavaScript: Body text, which needs 4.5:1
- In real life: How bright the chalk is on the dark board
- In JavaScript: The contrast ratio
Here is a page that checks the card's name the way WCAG does. It reads the colors Chrome computed with getComputedStyle(). Pick a style:
<link rel="stylesheet" href="tea-kit/tokens.css"><style>tea-card { --tea-card-accent: seagreen; }</style><tea-card name="Sencha" price="4"></tea-card><script src="contrast.js"></script><script type="module"> import "./tea-kit/index.js"; const card = document.querySelector("tea-card").shadowRoot; const name = getComputedStyle(card.querySelector("h3")); const paper = getComputedStyle(card.querySelector(".card")).backgroundColor; const points = parseFloat(name.fontSize) * 0.75; const large = points >= 18 || (Number(name.fontWeight) >= 700 && points >= 14); const needs = large ? 3 : 4.5; const got = ratio(name.color, paper); console.log(`Name: ${got} at ${name.fontSize}, ${large ? "large" : "normal"} text`); console.log(`Needs ${needs}:1, so it ${parseFloat(got) >= needs ? "passes" : "fails"}`);</script>4.24:1 is below 4.5:1. But the name is 18.72px and bold, which is 14 points bold, so it only needs 3:1.
- Line 2 is the line the playground changes: a custom property, or a ::part() rule.
- Lines 7 to 9 read the name and the card from the card's shadow root.
- Line 10 turns pixels into points: there are 0.75 points in a pixel.
- Line 11 is WCAG's rule: large means 18 points, or 14 points and bold.
- Line 13 runs the formula on the two colors Chrome computed.
- As it is:
Name: 4.24:1 at 18.72px, large text, thenNeeds 3:1, so it passes. - At 16px:
Name: 4.24:1 at 16px, normal text, thenNeeds 4.5:1, so it fails. - Medium sea green:
Name: 2.66:1 at 18.72px, large text, thenNeeds 3:1, so it fails. - Dark green:
Name: 7.43:1 at 18.72px, large text, thenNeeds 3:1, so it passes.
4.24:1 in both rows. Only the size changes, and with it the line the ratio has to clear.A color isn't good or bad on its own. The same sea green passes for the big name and fails for small text. Why it matters: check each pair at the size you really use it.
How much contrast do borders and controls need?
Text isn't the only thing Suresh has to see. He has to find the switch, and tell whether it's on. WCAG's 1.4.11, Non-text Contrast, covers that.
It asks for 3:1 for the parts you need to see a control and its state. The ratio is against the adjacent colors: the colors right next to that part. For a text box with a gray border on a white page, that's the border against the page.
The switch has two parts: the track and the round thumb. This page measures both, against what's next to each:
<link rel="stylesheet" href="tea-kit/tokens.css"><style>body { background: white; color: #222; }</style><tea-toggle>Add milk</tea-toggle><script src="contrast.js"></script><script type="module"> import "./tea-kit/index.js"; const toggle = document.querySelector("tea-toggle"); const fill = (selector) => getComputedStyle(toggle.shadowRoot.querySelector(selector)).backgroundColor; const page = getComputedStyle(document.body).backgroundColor; const show = () => { const state = toggle.checked ? "On" : "Off"; console.log(`${state}: track on page ${ratio(fill(".track"), page)}, thumb on track ${ratio(fill(".thumb"), fill(".track"))}`); }; show(); toggle.addEventListener("click", show);</script>- Line 2 gives the page a white background and dark text, so the script can read the page's color.
- Line 8 reads a part's fill from the switch's shadow root.
- Line 12 prints two ratios: the track against the page, and the thumb against the track.
- Line 15 prints again after each click.
It prints Off: track on page 5.48:1, thumb on track 5.48:1. Click the switch: On: track on page 4.24:1, thumb on track 4.24:1. Every part clears 3:1, in both states.
Notice what else changes when it's on: the thumb moves right. The state shows in position, not only in color. That matters for Arun, in the next section.
Some things don't need 3:1. WCAG leaves out controls that are turned off, and controls the browser draws without your styles. And a control needs no visible edge when its own text shows it's there. The badges aren't controls at all. What matters for them is their text, which needs 4.5:1 against the badge's own color.
Lesson 14.1 used the same rule for focus rings. Why it matters: if a person can't see a control's edge or its state, they can't use it.
How do you design for color blindness?
Arun has a color vision deficiency, often called color blindness. About 1 in 12 men and 1 in 200 women have one.
Our eyes have three kinds of color cells, called cones. One kind mostly senses red light, one green, and one blue. When one kind is missing or weak, some colors look alike. Reds, greens, and browns are common mix-ups. Chrome's DevTools can show you four kinds:
- Protanopia: little or no red. Greens, reds, and yellows get mixed up.
- Deuteranopia: little or no green. The same colors get mixed up, a little differently.
- Tritanopia: little or no blue. Greens and blues get mixed up.
- Achromatopsia: no color at all. Only light and dark are left.
To see your page that way, open DevTools and its Rendering tab. Pick one under Emulate vision deficiencies. Chrome draws it with an SVG color filter over the page, as Mathias Bynens explains. The numbers are in Chromium's source. A page can use the same filters, so this playground works in any browser:
<style>body { filter: none; }</style><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><p>Tie Guan Yin <tea-badge kind="oolong">Organic</tea-badge></p><p>Assam <tea-badge kind="black">Strong</tea-badge></p><p>Rooibos <tea-badge>Caffeine free</tea-badge></p><svg width="0" height="0" style="position: absolute" aria-hidden="true"> <filter id="protanopia"> <feColorMatrix values="0.152 1.053 -0.205 0 0 0.115 0.786 0.099 0 0 -0.004 -0.048 1.052 0 0 0 0 0 1 0" /> </filter> <filter id="deuteranopia"> <feColorMatrix values="0.367 0.861 -0.228 0 0 0.280 0.673 0.047 0 0 -0.012 0.043 0.969 0 0 0 0 0 1 0" /> </filter> <filter id="tritanopia"> <feColorMatrix values="1.256 -0.077 -0.179 0 0 -0.078 0.931 0.148 0 0 0.005 0.691 0.304 0 0 0 0 0 1 0" /> </filter> <filter id="achromatopsia"> <feColorMatrix values="0.213 0.715 0.072 0 0 0.213 0.715 0.072 0 0 0.213 0.715 0.072 0 0 0 0 0 1 0" /> </filter></svg><script type="module"> import "./tea-kit/index.js";</script>Dark green, brown, black, and gray. The legend says what each color means.
- Line 1 puts a filter on the whole page. It's the only line that changes.
- Lines 2 to 5 are the badges from the overview, and a plain gray one.
- Lines 6 to 19 hold Chrome's four filters. Each
feColorMatrixmixes every pixel's red, green, and blue into new ones.
- Protanopia: the green and oolong badges turn the same dull olive,
rgb(102, 89, 0)andrgb(103, 93, 41). They're only 1.06:1 apart. - Deuteranopia: two olives again, 1.51:1 apart. That's easy to miss.
- Tritanopia: green turns teal and brown turns pink. These four stay apart.
- Achromatopsia: the oolong badge and the plain one turn the same gray, 1.01:1 apart.
The course's test checks that each filter paints the same pixels as Chrome's own emulation.
Contrast didn't help here. Every badge has more than 4.5:1 between its text and its color. The trouble is that the color itself carries the meaning. WCAG's 1.4.1, Use of Color, says color can't be the only way to show information. Add a second cue:
- a word, like the kind's name;
- an icon, like a leaf;
- a pattern, like stripes;
- or an underline, for a link in a paragraph.
So the kit's new badge writes its kind. These are its new lines, from the tea-badge.js tab:
const kinds = new Map([
["green", "Green"],
["oolong", "Oolong"],
["black", "Black"],
]);
template.innerHTML = `<span id="kind" part="kind"></span> <slot></slot>`;
attributeChangedCallback(name, oldValue, newValue) {
this.shadowRoot.getElementById("kind").textContent = kinds.get(newValue) ?? "";
}- Lines 1 to 5 give each kind a name.
- Line 7 is the shadow root: a span for the kind, a space, then the slot for the badge's own text.
- Lines 9 to 11 run when
kindchanges. They write its name into the span, or nothing for an unknown kind.
<link rel="stylesheet" href="tea-kit/tokens.css"><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><p>Tie Guan Yin <tea-badge kind="oolong">Organic</tea-badge></p><p>Assam <tea-badge kind="black">Strong</tea-badge></p><script type="module"> import "./tea-kit/index.js"; for (const badge of document.querySelectorAll("tea-badge")) { console.log(badge.shadowRoot.getElementById("kind").textContent, badge.textContent); }</script>Line 8 prints each badge's kind and text: Green Organic, Oolong Organic, and Black Strong. Arun reads the kind now. The color is still there for everyone who sees it.
Why it matters: a color you can't tell apart is a blank. Give every meaning a word or a shape, and color becomes a bonus.
What is forced colors mode?
Farah turned on a contrast theme in Windows: Settings, Accessibility, Contrast themes. Now every app and every page uses a few colors she chose. People pick one to see better, to cut visual noise, or to ease eye strain, migraines, or light sensitivity, as Microsoft's Edge team writes. A theme can use any colors, even soft ones.
In a browser, this is forced colors mode. The browser replaces the page's colors with the person's palette. Here is what it changes. Read each row across:
| What you wrote | What forced colors mode does | What it means for a component |
|---|---|---|
| A text, background, border, or outline color. | It's replaced with one of the person's colors. | Your brand colors are gone. Shapes drawn only with a background vanish. |
A box-shadow or text-shadow. | It's turned off. | A ring or edge made only of a shadow disappears. |
| A gradient as a background image. | It's turned off. An image from a URL stays. | Don't draw anything important with a gradient. |
A system color, like CanvasText. | It's kept, in the person's palette. | Use these to bring back the parts that vanished. |
forced-color-adjust: none. | That element keeps the colors you wrote. | Keep it for a few things, like a color swatch. |
The browser also draws a backplate behind text: a solid block behind each line, so text stays readable over a picture. Pages can check for the mode with the media query @media (forced-colors: active).
Farah wears tinted glasses. Through them, every menu is white ink on black. The shop can't change what she sees through them, and shouldn't try. Its job is to make sure the menu still makes sense through them: every word, and the edge of every box.
- In real life: Farah's tinted glasses
- In JavaScript: The person's forced colors palette
- In real life: The shop's paint
- In JavaScript: The colors your CSS sets
- In real life: Words and box edges that still show
- In JavaScript: Text, borders, and outlines
A shadow root doesn't change any of this. The rules reach every element, inside a component or not:
<link rel="stylesheet" href="tea-kit/tokens.css"><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><tea-toggle>Add milk</tea-toggle><script type="module"> import "./tea-kit/index.js"; console.log("Forced colors:", matchMedia("(forced-colors: active)").matches); const fill = (element) => getComputedStyle(element).backgroundColor; const toggle = document.querySelector("tea-toggle").shadowRoot; console.log("Badge:", fill(document.querySelector("tea-badge"))); console.log("Track:", fill(toggle.querySelector(".track")), "Thumb:", fill(toggle.querySelector(".thumb")));</script>- Line 6 asks whether forced colors mode is on, with
matchMedia(). - Lines 9 and 10 print the fills of the badge, the track, and the thumb.
Normally it prints Forced colors: false, Badge: rgb(0, 100, 0), and Track: rgb(105, 105, 105) Thumb: rgb(255, 255, 255). Now turn on forced colors. In Chrome's DevTools, open the Rendering tab. Set Emulate CSS media feature forced-colors to forced-colors: active, and prefers-color-scheme to prefers-color-scheme: dark. Press Run again:
Forced colors: true.Badge: rgb(0, 0, 0).Track: rgb(0, 0, 0) Thumb: rgb(0, 0, 0).
Every fill is now black, the page's own color. The badge is a plain word. The track and thumb sit black on black, so the switch is gone. Only "Add milk" is left. That's what Farah saw.
Canvas, the page's own color. In Chrome's white-on-black palette, that's black on a black page.Testing forced colors mode in Chrome
The emulation is quick, but it isn't Windows. Here is what the course measured in Chrome:
- It has two palettes. With prefers-color-scheme set to dark, it's white text on black, with yellow links. With light, it's black text on white. That's why the steps above set both.
- It turns off
box-shadowand gradients, and keeps the system colors you write. - It doesn't change prefers-contrast, which stays at
no-preference. A real contrast theme sets it.
So test on Windows too, in Edge, Chrome, or Firefox. Left Alt, left Shift, and Print Screen turn a contrast theme on or off. Safari has the media feature, but it never matches active: Apple's systems have no forced colors mode.
Why it matters: anything you draw only with a background or a shadow can vanish for the people who need your page most.
What are CSS system colors?
So how does a component bring the switch back? It can't pick its own colors: they would fight Farah's palette. It has to use her colors, by name. Those names are the system colors.
A system color is a keyword for a job, not a color. Canvas means "the page's background", and CanvasText means "the text on it". The browser fills in the real color. Normally, that's its own default. In forced colors mode, it's the person's palette. And a system color you write is kept, never forced. So use system colors for any color forced colors mode doesn't override.
Regulars at Leaf and Kettle just say "the usual". Ravi doesn't write Sencha for Asha and Assam for Arun on the order. He writes "the usual", and each regular fills it in. The usual tea also comes in its usual cup.
- In real life: "The usual"
- In JavaScript: A system color, like
CanvasText - In real life: Each regular's own tea
- In JavaScript: Each person's palette
- In real life: The usual tea in its usual cup
- In JavaScript: A matching pair, like
CanvasandCanvasText
Use them in pairs. The CSS Color spec lists which pairs are meant to go together. Other pairs, like Canvas with ButtonText, aren't promised to contrast. Read the table across:
| Background | Text on it | What the pair is for | In Chrome's white-on-black palette |
|---|---|---|---|
Canvas | CanvasText | The page, and most text on it. | White text on black. |
ButtonFace | ButtonText | Buttons, and anything that acts like one. | White text on black. |
Field | FieldText | Text boxes and other fields. | White text on black. |
Highlight | HighlightText | Selected things, like the switch when it's on. | Black text on cyan. |
Canvas | LinkText | Links. | Yellow links on black. |
Canvas | GrayText | The text of something turned off. | Green text on black. |
The full list has more, like Mark and MarkText for marked text, and AccentColor for accented controls.
Now the switch. The kit's new version adds these rules at the end of its sheet, in the tea-toggle.js tab:
@media (forced-colors: active) {
.track { border: 1px solid CanvasText; padding: 1px; }
.thumb { background: CanvasText; }
:host(:state(checked)) .track { background: Highlight; }
:host(:state(checked)) .thumb { background: HighlightText; }
}- Line 1 matches only in forced colors mode.
- Line 2 gives the track an edge in the text color. It takes 1px of padding away, so the thumb still fits.
- Line 3 fills the thumb with the text color.
- Lines 4 and 5 use the pair for selected things,
HighlightandHighlightText, when the switch is on.
The badge gets one rule like it, so it keeps its shape:
@media (forced-colors: active) {
:host { border: 1px solid CanvasText; }
}<link rel="stylesheet" href="tea-kit/tokens.css"><p>Sencha <tea-badge kind="green">Organic</tea-badge></p><tea-toggle>Add milk</tea-toggle><script type="module"> import "./tea-kit/index.js"; console.log("Forced colors:", matchMedia("(forced-colors: active)").matches); const style = (element) => getComputedStyle(element); const border = (look) => (look.borderTopStyle === "none" ? "none" : look.borderTopColor); console.log("Badge border:", border(style(document.querySelector("tea-badge")))); const toggle = document.querySelector("tea-toggle"); const show = () => { const track = style(toggle.shadowRoot.querySelector(".track")); const thumb = style(toggle.shadowRoot.querySelector(".thumb")); console.log(`${toggle.checked ? "On" : "Off"}: track ${track.backgroundColor}, border ${border(track)}, thumb ${thumb.backgroundColor}`); }; show(); toggle.addEventListener("click", show);</script>- Line 9 prints the badge's border color, or none.
- Line 14 prints the track's fill, its border, and the thumb's fill.
- Line 17 prints again after each click.
Normally it prints Badge border: none, then Off: track rgb(105, 105, 105), border none, thumb rgb(255, 255, 255). Turn on the same two emulations, press Run again, and click the switch:
Badge border: rgb(255, 255, 255).Off: track rgb(0, 0, 0), border rgb(255, 255, 255), thumb rgb(255, 255, 255).On: track rgba(0, 230, 255, 0.8), border rgb(255, 255, 255), thumb rgb(0, 0, 0).
The switch is back: a white outline with a white thumb, then a cyan track with a black thumb. In the light palette, the same rules draw it black on white. The rules never named a color.
Why it matters: a few lines in the component's own sheet, in the person's own colors, make the control usable again. Nobody using the component has to do anything.
When should you use forced-color-adjust?
Sometimes the color is the content. Ravi adds tea-brew: a small round swatch showing the color each tea brews to. In forced colors mode, the swatch turns into the page's color like everything else, and the information is gone.
forced-color-adjust: none tells the browser to keep the colors you wrote on an element. It shouldn't be used to stop the person's own choices from being respected. So keep it for something like this swatch:
const template = document.createElement("template");
template.innerHTML = `
<style>
:host { display: flex; align-items: center; gap: 8px; color: saddlebrown; }
.swatch { width: 20px; height: 20px; border: 1px solid CanvasText; border-radius: 50%; background: var(--brew); }
.swatch { forced-color-adjust: none; }
</style>
<span class="swatch" part="swatch"></span><slot></slot>`;
customElements.define("tea-brew", class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).append(template.content.cloneNode(true));
}
});- Line 4 gives the words a brown color.
- Line 5 draws the swatch from the
--brewcustom property, with an edge inCanvasText. - Line 6 opts the swatch out of forced colors. The playground moves this rule.
<tea-brew style="--brew: gold">Sencha brews pale gold</tea-brew><tea-brew style="--brew: peru">Tie Guan Yin brews amber</tea-brew><tea-brew style="--brew: maroon">Assam brews deep red</tea-brew><script src="tea-brew.js"></script><script> console.log("Forced colors:", matchMedia("(forced-colors: active)").matches); const brew = document.querySelector("tea-brew"); const swatch = brew.shadowRoot.querySelector(".swatch"); console.log("Swatch:", getComputedStyle(swatch).backgroundColor, "Words:", getComputedStyle(brew).color);</script>In forced colors mode, the swatch stays gold. The words take the person's text color, white in Chrome's emulation.
Line 9 prints the first swatch's fill and the words' color. Normally both choices print Swatch: rgb(255, 215, 0) Words: rgb(139, 69, 19). With the two emulations on:
- On the swatch:
Swatch: rgb(255, 215, 0) Words: rgb(255, 255, 255). The swatch stays gold, and the words take Farah's text color. - On the host:
Swatch: rgb(255, 215, 0) Words: rgb(139, 69, 19). The words stay brown, on a black page. That's 2.95:1, too faint to read.
forced-color-adjust is inherited. On the host, it reaches the words too. On the swatch, it stops there.Why did the host version go wrong? forced-color-adjust is inherited, like color. Set on the host, it reaches the host's own words and everything in its shadow root. On the swatch, it stays on the swatch. The swatch still keeps an edge in CanvasText, so it shows on any page color.
It isn't in Safari. That costs nothing: Safari never turns forced colors mode on. Why it matters: opting out takes control away from the person, so do it for the swatch, never the component.
Do color-scheme and light-dark() work in shadow DOM?
Yes. Lesson 2.3 showed it, after Burton Smith pointed it out. color-scheme is inherited, so it reaches into shadow roots. light-dark() picks its first color in a light scheme and its second in a dark one. Two more things matter for contrast.
First, light-dark() is worked out where it's used, not where it's written. So a kit token made with it picks the right side inside a component:
<style> :root { --tea-note: light-dark(darkgreen, palegreen); } .day { color-scheme: light; } .evening { color-scheme: dark; } .day, .evening { background: Canvas; padding: 4px 12px; }</style><div class="day"><tea-note>Day</tea-note></div><div class="evening"><tea-note>Evening</tea-note></div><script> customElements.define("tea-note", class extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = `<p style="color: var(--tea-note)"><slot></slot></p>`; } }); for (const note of document.querySelectorAll("tea-note")) { console.log(note.textContent, getComputedStyle(note.shadowRoot.querySelector("p")).color); }</script>- Line 2 makes one token on the page's root.
- Lines 3 to 5 make a light box and a dark box.
- Line 13 uses the token inside the shadow root.
It prints Day rgb(0, 100, 0) and Evening rgb(152, 251, 152): dark green in the light box, pale green in the dark one. Adobe's tests found the same: light-dark() works through custom properties in shadow roots. System colors follow the scheme too. In Chrome, Canvas is white in a light scheme and rgb(18, 18, 18) in a dark one.
Second, a dark scheme breaks a component that sets only half its colors. The card sets its background to white, but its text color comes from the page:
<link rel="stylesheet" href="tea-kit/tokens.css"><style> .day { color-scheme: light; } .evening { color-scheme: dark; } .day, .evening { background: Canvas; color: CanvasText; padding: 8px; }</style><div class="day"><tea-card name="Sencha" price="4"></tea-card></div><div class="evening"><tea-card name="Sencha" price="4"></tea-card></div><script src="contrast.js"></script><script type="module"> import "./tea-kit/index.js"; for (const box of document.querySelectorAll(".day, .evening")) { const card = box.querySelector("tea-card").shadowRoot; const paper = getComputedStyle(card.querySelector(".card")).backgroundColor; const price = getComputedStyle(card.querySelector("#price")).color; console.log(`${box.className}: price ${price} on ${paper}, ${ratio(price, paper)}`); }</script>The evening box makes the inherited text white. The card sets its background but not its text, so the price vanishes.
- Lines 3 to 5 make the boxes, each with the browser's own text color for its scheme.
- Lines 14 and 15 read the card's paper and the price's color, from the shadow root.
- kitAfter145:
day: price rgb(0, 0, 0) on rgb(255, 255, 255), 21.00:1, butevening: price rgb(255, 255, 255) on rgb(255, 255, 255), 1.00:1. White on white. - kitAfter151: both lines end
15.90:1.
WCAG lists this as failure F24: setting a background without a text color, or the other way round. The fix is one declaration in the card's .card rule, next to its background: color: var(--tea-color-ink, #222).
Forced colors mode overrides the scheme too: color-scheme is forced to light dark, and Chrome's emulation shows it. With a real contrast theme, the browser matches prefers-color-scheme to how dark the theme's Canvas is, as the spec says.
Why it matters: a component that sets its background must set its text color too, in every scheme it can land in.
Auditing the tea kit's colors
Ravi audits every pair of colors the kit uses. For each pair, he notes where it's used, at what size, and what WCAG asks. Then he runs the formula on the colors Chrome computed. Here is the audit page, before and after this lesson:
<link rel="stylesheet" href="tea-kit/tokens.css"><link rel="stylesheet" href="tea-kit/light.css"><style>body { background: white; color: #222; }</style><tea-filter> <form><input type="search" aria-label="Find a tea"> <button>Find</button></form> <ul> <li>Sencha <tea-badge kind="green">Organic</tea-badge></li> <li>Tie Guan Yin <tea-badge kind="oolong">Organic</tea-badge></li> <li>Assam <tea-badge kind="black">Strong</tea-badge></li> </ul></tea-filter><tea-card name="Sencha" price="4"></tea-card><script src="contrast.js"></script><script type="module"> import "./tea-kit/index.js"; const style = (element) => getComputedStyle(element); const check = (what, text, box, needs) => { console.log(`${what}: ${ratio(style(text).color, style(box).backgroundColor)}, needs ${needs}:1`); }; const find = document.querySelector("tea-filter button"); check("Find button", find, find, 4.5); for (const badge of document.querySelectorAll("tea-badge")) check(`${badge.getAttribute("kind")} badge`, badge, badge, 4.5); const card = document.querySelector("tea-card").shadowRoot; check("Card name", card.querySelector("h3"), card.querySelector(".card"), 3);</script>light.css gave the button sea green text at 16px: 4.24:1, below the 4.5:1 that body-size text needs.
- Line 2 links
light.css, the kit's styles for its light DOM components from lesson 12.4. - Lines 17 to 19 make
check(). It prints one pair's ratio and the line it needs to clear. - Lines 21 to 24 check the Find button, each badge, and the card's name.
Before, the first line is Find button: 4.24:1, needs 4.5:1. The kit gave that button sea green text at 16px. After, it's Find button: 15.90:1, needs 4.5:1. The other lines pass both times. Here is the whole audit. Read each row across:
| Which colors | Where the kit uses them | What WCAG asks | What Chrome measured |
|---|---|---|---|
| Ink on paper. | The card's text and the Find button's text, after this lesson. | 4.5:1, for any text. | 15.90:1. It passes. |
| Stone on paper. | The quantity's hint text, the search box's border, and the switch's off track. | 4.5:1 for the hint, 3:1 for the parts. | 5.48:1. It passes. |
| Leaf on paper. | The card's name, borders, rings, and the switch's on track. | 3:1, because the name is large text. | 4.24:1. It passes. |
| Leaf on paper, at 16px. | The Find button's text, before this lesson. | 4.5:1, because 16px is body text. | 4.24:1. It failed, so the button now uses ink. |
| Paper on each badge. | The badges' text on gray, green, brown, and black. | 4.5:1. | 5.48:1, 7.43:1, 5.61:1, and 21.00:1. They pass. |
| The card's text in a dark box. | The price, before this lesson. | 4.5:1. | 1.00:1. It failed, so the card now sets its text color. |
The fixes are in the kit's new version, kitAfter151, so later lessons build on them. Five files changed:
tokens.cssgets--tea-color-ink, and a note of each token's ratio on paper.light.cssgives the Find button ink for its text. Its border keeps the leaf green.tea-cardsets its text color with its background.tea-badgewrites its kind, and draws aCanvasTextborder in forced colors mode.tea-togglegets its forced colors rules.
/* The tea kit's design tokens: the values every component shares. Link it in the page's head. */
@layer tea-kit {
:root {
/* On paper, ink (15.90:1) and stone (5.48:1) suit any text. Leaf (4.24:1) is for large text, borders, and rings. */
--tea-color-leaf: seagreen;
--tea-color-paper: white;
--tea-color-ink: #222;
--tea-color-stone: dimgray;
--tea-focus-ring: var(--tea-color-leaf);
--tea-radius: 8px;
--tea-space: 8px;
--tea-motion: 1;
}
}- Line 4 notes each token's ratio on paper, and what leaf is for.
- Line 7 is the new ink token. Custom properties reach into shadow roots, as lesson 12.1 showed, so every component can use it.
Every other file stays as it was. The kit's JSDoc and custom-elements.json describe the badge's new kind part, the card's ink, and the switch's forced colors.
- The card's price, in dark text on the white card.
- The card's name: 18.72px, bold, in sea green.
- The search box's gray border on the white page.
- The switch's track on the white page.
- Green, brown, and black badges that are the only way to tell the kinds of tea apart.
- A text box whose border turns red when the email is wrong, with no message.
Sort each part of the menu by the rule that covers it.
Why it matters: fix a color in the token, and every component that uses it is fixed at once.
Common mix-ups
- "If a color passes contrast, it's accessible." No. Sea green passes for the big name and fails for 16px text. And badges that pass 4.5:1 still fail 1.4.1 when color is their only cue.
- "4.49:1 is close enough to 4.5:1." No. WCAG compares without rounding.
- "A shadow root keeps a component's colors safe from forced colors mode." No. The rules reach inside. The kit's switch vanished.
- "Colors from custom properties survive forced colors mode." No.
var()gives a color like any other, and it's replaced. - "forced-color-adjust: none on the host is a quick fix." No. It's inherited, so every word inside ignores the person's colors.
- "DevTools' forced colors shows what Windows users see." No. It has two fixed palettes, and it leaves prefers-contrast alone. Test a real contrast theme too.
- "System colors only work in forced colors mode." No. They always work. Normally they're the browser's defaults, which follow
color-scheme.
Practice exercises
Ravi writes brewing notes in gray. What does the page print, and is that enough for body text?
<style> body { background: white; } .note { color: #777; }</style><p class="note">Steep for three minutes.</p><script src="contrast.js"></script><script> const note = getComputedStyle(document.querySelector(".note")); console.log(`Note: ${ratio(note.color, getComputedStyle(document.body).backgroundColor)}`);</script><style> body { background: white; } .note { color: #767676; }</style><p class="note">Steep for three minutes.</p><script src="contrast.js"></script><script> const note = getComputedStyle(document.querySelector(".note")); console.log(`Note: ${ratio(note.color, getComputedStyle(document.body).backgroundColor)}`);</script>It prints Note: 4.47:1, which fails 4.5:1: WCAG never rounds. Line 3 changes to #767676, one step darker. The page prints Note: 4.54:1, a pass.
Line 2 makes the card's name 20px and not bold. Predict the second line it prints. Then make it pass by size alone.
<link rel="stylesheet" href="tea-kit/tokens.css"><style>tea-card::part(name) { font-size: 20px; font-weight: normal; }</style><tea-card name="Sencha" price="4"></tea-card><script src="contrast.js"></script><script type="module"> import "./tea-kit/index.js"; const card = document.querySelector("tea-card").shadowRoot; const name = getComputedStyle(card.querySelector("h3")); const paper = getComputedStyle(card.querySelector(".card")).backgroundColor; const points = parseFloat(name.fontSize) * 0.75; const large = points >= 18 || (Number(name.fontWeight) >= 700 && points >= 14); const needs = large ? 3 : 4.5; const got = ratio(name.color, paper); console.log(`Name: ${got} at ${name.fontSize}, ${large ? "large" : "normal"} text`); console.log(`Needs ${needs}:1, so it ${parseFloat(got) >= needs ? "passes" : "fails"}`);</script><link rel="stylesheet" href="tea-kit/tokens.css"><style>tea-card::part(name) { font-size: 24px; font-weight: normal; }</style><tea-card name="Sencha" price="4"></tea-card><script src="contrast.js"></script><script type="module"> import "./tea-kit/index.js"; const card = document.querySelector("tea-card").shadowRoot; const name = getComputedStyle(card.querySelector("h3")); const paper = getComputedStyle(card.querySelector(".card")).backgroundColor; const points = parseFloat(name.fontSize) * 0.75; const large = points >= 18 || (Number(name.fontWeight) >= 700 && points >= 14); const needs = large ? 3 : 4.5; const got = ratio(name.color, paper); console.log(`Name: ${got} at ${name.fontSize}, ${large ? "large" : "normal"} text`); console.log(`Needs ${needs}:1, so it ${parseFloat(got) >= needs ? "passes" : "fails"}`);</script>It prints Needs 4.5:1, so it fails. 20px is 15 points, and the name is no longer bold. Line 2 changes to 24px: 18 points, so it's large text and needs only 3:1. The page prints Needs 3:1, so it passes.
tea-stock shows a green dot for in stock and a red one for sold out. Make it write the word too. What does the page print then?
<p>Sencha <tea-stock state="in"></tea-stock></p><p>Assam <tea-stock state="out"></tea-stock></p><script src="tea-stock.js"></script><script> for (const stock of document.querySelectorAll("tea-stock")) { console.log(`${stock.getAttribute("state")}: "${stock.shadowRoot.getElementById("word").textContent}"`); }</script><p>Sencha <tea-stock state="in"></tea-stock></p><p>Assam <tea-stock state="out"></tea-stock></p><script src="tea-stock.js"></script><script> for (const stock of document.querySelectorAll("tea-stock")) { console.log(`${stock.getAttribute("state")}: "${stock.shadowRoot.getElementById("word").textContent}"`); }</script>The tea-stock.js tab changes: its callback writes the word into the span. The page prints in: "In stock" and out: "Sold out". Now the dot's color is a second cue, not the only one, as WCAG 1.4.1 asks.
Turn on forced colors in DevTools. The page prints Dot is the text color: false: the dot is gone. Fix it in the component's own sheet. What does the second line say then?
<p>Sencha <tea-stock state="in"></tea-stock></p><p>Assam <tea-stock state="out"></tea-stock></p><script src="tea-stock.js"></script><script> console.log("Forced colors:", matchMedia("(forced-colors: active)").matches); const dot = getComputedStyle(document.querySelector("tea-stock").shadowRoot.querySelector(".dot")); console.log("Dot is the text color:", dot.backgroundColor === getComputedStyle(document.body).color);</script><p>Sencha <tea-stock state="in"></tea-stock></p><p>Assam <tea-stock state="out"></tea-stock></p><script src="tea-stock.js"></script><script> console.log("Forced colors:", matchMedia("(forced-colors: active)").matches); const dot = getComputedStyle(document.querySelector("tea-stock").shadowRoot.querySelector(".dot")); console.log("Dot is the text color:", dot.backgroundColor === getComputedStyle(document.body).color);</script>The tea-stock.js tab gets one rule. CanvasText is a system color, so it's kept, and it's the person's text color. In forced colors mode, the page prints Dot is the text color: true, in either of Chrome's palettes.
With forced colors and a dark scheme on, the words stay brown on black. Fix the component. What color are the words then?
<tea-brew style="--brew: gold">Sencha brews pale gold</tea-brew><tea-brew style="--brew: peru">Tie Guan Yin brews amber</tea-brew><tea-brew style="--brew: maroon">Assam brews deep red</tea-brew><script src="tea-brew.js"></script><script> console.log("Forced colors:", matchMedia("(forced-colors: active)").matches); const brew = document.querySelector("tea-brew"); const swatch = brew.shadowRoot.querySelector(".swatch"); console.log("Swatch:", getComputedStyle(swatch).backgroundColor, "Words:", getComputedStyle(brew).color);</script><tea-brew style="--brew: gold">Sencha brews pale gold</tea-brew><tea-brew style="--brew: peru">Tie Guan Yin brews amber</tea-brew><tea-brew style="--brew: maroon">Assam brews deep red</tea-brew><script src="tea-brew.js"></script><script> console.log("Forced colors:", matchMedia("(forced-colors: active)").matches); const brew = document.querySelector("tea-brew"); const swatch = brew.shadowRoot.querySelector(".swatch"); console.log("Swatch:", getComputedStyle(swatch).backgroundColor, "Words:", getComputedStyle(brew).color);</script>Line 6 of the tea-brew.js tab becomes .swatch { forced-color-adjust: none; }. Only the swatch keeps its gold. The words are forced to the person's text color: Words: rgb(255, 255, 255) with the dark palette.
The page prints day: 21.00:1 and evening: 1.00:1. Fix tea-receipt so both pass. What does the evening line print then?
<style> .day { color-scheme: light; } .evening { color-scheme: dark; } .day, .evening { background: Canvas; color: CanvasText; padding: 8px; }</style><div class="day"><tea-receipt>$8</tea-receipt></div><div class="evening"><tea-receipt>$8</tea-receipt></div><script src="tea-receipt.js"></script><script src="contrast.js"></script><script> for (const box of document.querySelectorAll(".day, .evening")) { const total = getComputedStyle(box.querySelector("tea-receipt").shadowRoot.querySelector("p")); console.log(`${box.className}: ${ratio(total.color, total.backgroundColor)}`); }</script><style> .day { color-scheme: light; } .evening { color-scheme: dark; } .day, .evening { background: Canvas; color: CanvasText; padding: 8px; }</style><div class="day"><tea-receipt>$8</tea-receipt></div><div class="evening"><tea-receipt>$8</tea-receipt></div><script src="tea-receipt.js"></script><script src="contrast.js"></script><script> for (const box of document.querySelectorAll(".day, .evening")) { const total = getComputedStyle(box.querySelector("tea-receipt").shadowRoot.querySelector("p")); console.log(`${box.className}: ${ratio(total.color, total.backgroundColor)}`); }</script>The tea-receipt.js tab's rule gets color: #222 next to background: white. That fixes failure F24. Both lines print 15.90:1: day: 15.90:1 and evening: 15.90:1.
Check your understanding
Question 1 of 8The card's name is sea green on white, 4.24:1, at 18.72px and bold. Does it pass WCAG 1.4.3?
Choose an answer to see the explanation.
Question 2 of 8A note's gray text measures 4.499:1 on its white background. Does it pass for body text?
Choose an answer to see the explanation.
Question 3 of 8Green, brown, and black badges are the only thing that tells the kinds of tea apart. Each passes 4.5:1. What fails?
Choose an answer to see the explanation.
Question 4 of 8In forced colors mode, what happens to the switch in kitAfter145?
Choose an answer to see the explanation.
Question 5 of 8Why does kitAfter151 give the switch's thumb
background: CanvasTextinside@media (forced-colors: active)?Choose an answer to see the explanation.
Question 6 of 8tea-brew's swatch must keep its real color. Where should
forced-color-adjust: nonego?Choose an answer to see the explanation.
Question 7 of 8What does the evening line print with kitAfter145?
Read the code, then predict<link rel="stylesheet" href="tea-kit/tokens.css"> <style> .day { color-scheme: light; } .evening { color-scheme: dark; } .day, .evening { background: Canvas; color: CanvasText; padding: 8px; } </style> <div class="day"><tea-card name="Sencha" price="4"></tea-card></div> <div class="evening"><tea-card name="Sencha" price="4"></tea-card></div> <script src="contrast.js"></script> <script type="module"> import "./tea-kit/index.js"; for (const box of document.querySelectorAll(".day, .evening")) { const card = box.querySelector("tea-card").shadowRoot; const paper = getComputedStyle(card.querySelector(".card")).backgroundColor; const price = getComputedStyle(card.querySelector("#price")).color; console.log(`${box.className}: price ${price} on ${paper}, ${ratio(price, paper)}`); } </script>Choose an answer to see the explanation.
Question 8 of 8You turn on forced colors in DevTools' Rendering tab. What doesn't Chrome's emulation change?
Choose an answer to see the explanation.
Key takeaways
- Text needs 4.5:1. Large text, 18 points or 14 points bold, needs 3:1. Never round a ratio up.
- The parts of a control, and its states, need 3:1 against the colors next to them.
- Color can't be the only cue. Add a word, an icon, or a shape, and check with DevTools' vision deficiency emulation.
- Forced colors mode replaces colors and turns off shadows and gradients, inside shadow roots too.
- In the component's own sheet, use
@media (forced-colors: active)and system colors in pairs to bring back what vanished. - Use
forced-color-adjust: noneonly on things like swatches, never on a host. - Whenever a component sets its background, it sets its text color too.
Remember the one-liner.
Measure every pair, never trust color alone, and let the person's colors win.
Sources
The facts on this page come from these standards, docs, and posts:
- Understanding SC 1.4.3: Contrast (Minimum), W3C WAI.
- Color contrast, MDN.
- Understanding SC 1.4.11: Non-text Contrast, W3C WAI.
- Understanding SC 1.4.1: Use of Color, W3C WAI.
- About colour blindness, Colour Blind Awareness.
- Types of colour blindness, Colour Blind Awareness.
- Emulate vision deficiencies, Chrome DevTools docs.
- Simulating color vision deficiencies in the Blink Renderer, Mathias Bynens, Chrome for Developers.
- vision_deficiency.cc, Chromium 158.0.8127.18, Chromium source.
- forced-colors, MDN.
- Change color contrast in Windows, Microsoft Support.
- Styling for Windows high contrast with new standards for forced colors, Microsoft Edge Team.
- CSS Color Adjustment Module Level 1: forced color palettes, W3C CSS Working Group.
- Emulate CSS media feature forced-colors, Chrome DevTools docs.
- <system-color>, MDN.
- CSS Color Module Level 4: system colors, W3C CSS Working Group.
- forced-color-adjust, MDN.
- Dark Mode in Web Components is About to Get AWESOME!, Burton Smith.
- Modern CSS Feature Support For Shadow DOM: light-dark(), Adobe Spectrum Web Engineering.
- Failure F24: foreground colors without background colors, W3C WAI.
- prefers-contrast, MDN.
- browser-compat-data, MDN.
Coming next: Right-to-left and logical properties, in Accessible components. It builds components that flip correctly for right-to-left languages.