WCAG 2.2 color contrast and form accessibility are where most websites fail an accessibility audit, and both are easy to fix once you know the numbers. Light grey placeholder text, pale input borders, white text on a mid-blue button, a form that only marks errors in red: each of these breaks a specific WCAG 2.2 success criterion and makes the page harder to use for people with low vision, colour blindness, motor impairments or cognitive disabilities, and for anyone on a phone in sunlight. This guide covers the contrast rules and how the ratio is calculated, a Python script that checks your design tokens and suggests passing colors, the markup patterns for accessible labels, hints and errors, the criteria that are new in WCAG 2.2, and automated tests with axe-core so regressions are caught in CI.

WCAG 2.2 color contrast and accessible forms workflow: check text and UI contrast ratios, label every field, write clear error messages, add autocomplete and test with axe-core
Contrast ratios and form markup cover most WCAG 2.2 failures on typical business sites, and both can be checked automatically.

From my own work: In the site audits I run, the same three findings come back on almost every project: placeholder text used as the only label, input borders that are nearly invisible against white, and error messages shown only as a red border. All three are design-token or component fixes, so one change repairs every form on the site.

WCAG 2.2 color contrast requirements

WCAG 2.2 has three contrast success criteria that matter in everyday design work (W3C: WCAG 2.2). Level AA is the target that laws and procurement rules usually reference, including the European Accessibility Act through the EN 301 549 standard.

Criterion Level Applies to Minimum ratio
1.4.3 Contrast (Minimum) AA Body text, labels, placeholder text, button text, links 4.5:1
1.4.3 Contrast (Minimum), large text AA Text at least 18pt (about 24px) or 14pt bold (about 18.66px bold) 3:1
1.4.11 Non-text Contrast AA Input borders, checkboxes, focus indicators, icons and chart lines needed to understand content 3:1 against adjacent colors
1.4.6 Contrast (Enhanced) AAA Normal text / large text 7:1 / 4.5:1

Logos, purely decorative text and disabled controls are exempt (W3C: Understanding contrast minimum). Placeholder text is not exempt; if you show it, it needs 4.5:1 like any other text. Non-text contrast applies to the parts of a control that users need to see to identify it and its state, so a text field whose only visible boundary is a 1px border needs that border at 3:1 against the page background (W3C: Understanding non-text contrast).

How the contrast ratio is calculated

The ratio compares the relative luminance of the lighter color (L1) and the darker color (L2): (L1 + 0.05) / (L2 + 0.05). It ranges from 1:1 (same color) to 21:1 (black on white). Relative luminance converts each sRGB channel to a linear value and weights green most heavily, because human vision is most sensitive to it:

channel = value / 255
linear  = channel / 12.92                       if channel <= 0.04045
        = ((channel + 0.055) / 1.055) ** 2.4    otherwise
L = 0.2126 * R_linear + 0.7152 * G_linear + 0.0722 * B_linear

This is why #767676 on white (4.54:1) passes for body text while #777777 (4.48:1) does not, even though they look identical. Never judge contrast by eye; calculate it.

A Python contrast checker for design tokens

Checking colors one at a time in a browser tool does not scale to a design system. Put the pairs your components actually use into a CSV, then let a script check them and propose the nearest passing color. The script needs only the Python standard library:

"""Check WCAG 2.2 contrast for design-token color pairs.

Usage: python contrast_check.py pairs.csv
pairs.csv columns: name,foreground,background,kind   (kind = text | large | ui)
"""
from __future__ import annotations

import csv
import sys

REQUIRED = {"text": 4.5, "large": 3.0, "ui": 3.0}


def hex_to_rgb(value: str) -> tuple[float, float, float]:
    value = value.strip().lstrip("#")
    if len(value) == 3:
        value = "".join(ch * 2 for ch in value)
    return tuple(int(value[i:i + 2], 16) / 255 for i in (0, 2, 4))


def channel(c: float) -> float:
    return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4


def luminance(hex_color: str) -> float:
    r, g, b = (channel(c) for c in hex_to_rgb(hex_color))
    return 0.2126 * r + 0.7152 * g + 0.0722 * b


def contrast_ratio(fg: str, bg: str) -> float:
    l1, l2 = sorted((luminance(fg), luminance(bg)), reverse=True)
    return (l1 + 0.05) / (l2 + 0.05)


def darken_until(dark: str, light: str, target: float) -> str | None:
    """Scale the darker color toward black until the pair meets the target."""
    r, g, b = hex_to_rgb(dark)
    for step in range(101):
        k = 1 - step / 100
        candidate = "#{:02x}{:02x}{:02x}".format(*(round(c * k * 255) for c in (r, g, b)))
        if contrast_ratio(candidate, light) >= target:
            return candidate
    return None


if __name__ == "__main__":
    failed = 0
    with open(sys.argv[1], newline="", encoding="utf-8") as fh:
        for row in csv.DictReader(fh):
            need = REQUIRED[row["kind"]]
            ratio = contrast_ratio(row["foreground"], row["background"])
            ok = ratio >= need
            line = f"{'PASS' if ok else 'FAIL'}  {row['name']:<24} {ratio:5.2f}:1  (needs {need}:1)"
            if not ok:
                failed += 1
                fg, bg = row["foreground"], row["background"]
                if luminance(fg) <= luminance(bg):
                    fix, which = darken_until(fg, bg, need), "foreground"
                else:
                    fix, which = darken_until(bg, fg, need), "background"
                line += f"  try {which} {fix}" if fix else "  pick a new pair"
            print(line)
    sys.exit(1 if failed else 0)
name,foreground,background,kind
body-text,#333333,#ffffff,text
placeholder,#a0a0a0,#ffffff,text
muted-label,#767676,#ffffff,text
link,#2f80ed,#ffffff,text
button-text,#ffffff,#3b82f6,text
input-border,#d1d5db,#ffffff,ui
focus-ring,#2563eb,#ffffff,ui
hero-heading,#9ca3af,#ffffff,large
$ python contrast_check.py pairs.csv
PASS  body-text                12.63:1  (needs 4.5:1)
FAIL  placeholder               2.61:1  (needs 4.5:1)  try foreground #767676
PASS  muted-label               4.54:1  (needs 4.5:1)
FAIL  link                      3.87:1  (needs 4.5:1)  try foreground #2b74d8
FAIL  button-text               3.68:1  (needs 4.5:1)  try background #3472d8
FAIL  input-border              1.47:1  (needs 3.0:1)  try foreground #929599
PASS  focus-ring                5.17:1  (needs 3.0:1)
FAIL  hero-heading              2.54:1  (needs 3.0:1)  try foreground #8e949f

The suggestion keeps the hue and only darkens the darker color of the pair, which is usually the least disruptive fix for a brand palette. The script exits with status 1 when any pair fails, so it can run as a CI step whenever the token file changes. Check dark mode tokens as a separate set of pairs, and remember that text over images or gradients must pass against the lightest area behind it; a solid or semi-opaque overlay is the reliable fix.

Accessible form markup: labels, hints and groups

Every input needs a programmatic label, and WCAG 3.3.2 Labels or Instructions expects it to be visible. A placeholder is not a label: it disappears as soon as the user types, it is often low contrast, and some assistive technology does not announce it reliably. The W3C forms tutorial shows the patterns below (W3C WAI: forms tutorial):

<form action="/contact/" method="post" novalidate>
  <div class="field">
    <label for="name">Full name</label>
    <input id="name" name="name" type="text" autocomplete="name" required>
  </div>

  <div class="field">
    <label for="email">Email address</label>
    <p id="email-hint" class="hint">We reply within one business day.</p>
    <input id="email" name="email" type="email" autocomplete="email"
           required aria-describedby="email-hint">
  </div>

  <fieldset>
    <legend>Preferred contact method</legend>
    <label><input type="radio" name="contact" value="email" checked> Email</label>
    <label><input type="radio" name="contact" value="phone"> Phone</label>
  </fieldset>

  <div class="field">
    <label for="phone">Phone number <span class="optional">(optional)</span></label>
    <input id="phone" name="tel" type="tel" autocomplete="tel">
  </div>

  <button type="submit">Send message</button>
</form>
  • Explicit labels with for and id also make the label clickable, which enlarges the target for checkboxes and radios.
  • Hints go before the input and are linked with aria-describedby, so screen readers read them after the label.
  • Groups of radios or checkboxes use fieldset and legend, so the question is announced with each option.
  • Required fields use the required attribute plus a visible marker or, as here, marking the optional fields instead. Explain the convention once at the top of long forms.

autocomplete values such as name, email, tel, street-address, postal-code and one-time-code satisfy WCAG 1.3.5 Identify Input Purpose and let browsers and password managers fill fields correctly (MDN: autocomplete attribute). That helps people with motor and memory impairments most, and it shortens every checkout and lead form, which matters for the conversion work described in the conversion rate optimization guide.

Error messages that meet WCAG 2.2

WCAG 3.3.1 Error Identification requires errors to be described in text, and 1.4.1 Use of Color means a red border alone is not enough. 3.3.3 Error Suggestion adds that you should say how to fix the problem when you know. A pattern that covers all three:

<div class="field field--error">
  <label for="email">Email address</label>
  <p id="email-error" class="error">
    <svg aria-hidden="true" width="16" height="16"><use href="#icon-alert"></use></svg>
    Enter an email address in the format name@example.com
  </p>
  <input id="email" name="email" type="email" autocomplete="email" required
         aria-invalid="true" aria-describedby="email-error email-hint">
</div>
// After server or client validation fails
function showErrors(form, errors) {
  const summary = form.querySelector("#error-summary");
  summary.innerHTML = "<h2>There is a problem</h2><ul>" +
    errors.map(e => `<li><a href="#${e.field}">${e.message}</a></li>`).join("") +
    "</ul>";
  summary.hidden = false;
  summary.focus();                 // summary has tabindex="-1"

  for (const e of errors) {
    const input = form.querySelector(`#${e.field}`);
    input.setAttribute("aria-invalid", "true");
  }
}

Moving focus to an error summary with links to each field works for keyboard, screen reader and sighted users alike. Keep the message text specific (what is wrong and the expected format), keep the user’s input in the field, and never clear the whole form on a failed submit. Give error text the same 4.5:1 contrast as body text; many brand reds on white fall below it.

What is new in WCAG 2.2 for forms and focus

Criterion Level What to do
2.4.11 Focus Not Obscured (Minimum) AA A focused field must not be fully hidden by sticky headers, cookie banners or chat widgets. Use scroll-padding-top for sticky headers.
2.4.13 Focus Appearance AAA A focus indicator at least as large as a 2 CSS pixel perimeter with 3:1 change in contrast.
2.5.8 Target Size (Minimum) AA Click and tap targets at least 24 by 24 CSS pixels, or enough spacing around smaller ones.
3.3.7 Redundant Entry A Do not ask for the same information twice in one process; prefill it or offer “same as billing address”.
3.3.8 Accessible Authentication (Minimum) AA No memory or puzzle test to log in unless there is an alternative. Allow paste and password managers; do not block them on password and code fields.
/* Visible, high-contrast focus for every interactive element */
:where(a, button, input, select, textarea, [tabindex]):focus-visible {
  outline: 3px solid #2563eb;      /* 5.17:1 on white */
  outline-offset: 2px;
}

/* Input boundaries at 3:1 or more against the page */
input, select, textarea {
  border: 1px solid #8a8f98;
  min-height: 44px;                /* comfortably above the 24px minimum */
}

/* Keep focused fields clear of a 72px sticky header */
html { scroll-padding-top: 88px; }

/* Respect Windows High Contrast and other forced color modes */
@media (forced-colors: active) {
  :focus-visible { outline-color: Highlight; }
}

WCAG 4.1.1 Parsing was removed in 2.2, so duplicate attributes and minor HTML errors no longer fail on their own; the related problems that do affect users are covered by 4.1.2 Name, Role, Value.

Test contrast and forms automatically with axe-core

axe-core is the open-source rules engine behind many accessibility tools. It tags rules by WCAG version and level, so you can run exactly the AA set (axe-core). A Playwright test checks a form both before and after a failed submit, because the error state is where most problems hide:

npm install --save-dev @playwright/test @axe-core/playwright
npx playwright install chromium
// tests/a11y-contact.spec.ts
import { test, expect } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";

const WCAG_AA = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"];

test("contact form meets WCAG 2.2 AA", async ({ page }) => {
  await page.goto("/contact/");
  const initial = await new AxeBuilder({ page }).withTags(WCAG_AA).analyze();
  expect(initial.violations).toEqual([]);

  await page.getByRole("button", { name: "Send message" }).click();
  await expect(page.locator("#error-summary")).toBeFocused();

  const withErrors = await new AxeBuilder({ page }).withTags(WCAG_AA).analyze();
  expect(withErrors.violations).toEqual([]);
});
# quick check of a live URL from the command line (needs Chrome installed)
npx @axe-core/cli https://example.com/contact/ --tags wcag2aa,wcag22aa --exit

Automated rules catch contrast, missing labels, invalid ARIA and duplicate IDs, but not whether a label makes sense, whether the error text is helpful or whether the focus order is logical. Add a five-minute manual pass for each new form: complete it with the keyboard only, zoom to 200 percent, and listen to it once with a screen reader such as NVDA or VoiceOver.

Accessibility and technical SEO overlap in semantic structure, which is covered in semantic HTML5 and accessibility. Larger touch targets and stable layouts also help the mobile experience measured in Core Web Vitals on mobile.

WCAG 2.2 color contrast and forms checklist

  • Text and placeholders at 4.5:1; large text at 3:1; borders, icons and focus rings at 3:1.
  • Every token pair checked by a script in CI, including dark mode and text over images.
  • Visible labels linked with for; hints and errors linked with aria-describedby; groups in fieldset.
  • Correct type and autocomplete on every personal-data field.
  • Errors in text with an icon, a summary that receives focus, and input preserved.
  • Visible :focus-visible styles, not hidden behind sticky elements; targets at least 24 by 24 pixels.
  • No repeated entry, paste allowed on password and code fields.
  • axe-core tests for the default and error states, plus a keyboard and screen reader pass.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

What is the minimum color contrast ratio in WCAG 2.2?

For Level AA, normal text needs at least 4.5:1 against its background and large text (18pt, or 14pt bold) needs 3:1. User interface components and meaningful graphics need 3:1 against adjacent colors under the non-text contrast criterion.

Does placeholder text need to meet contrast requirements?

Yes. Placeholder text is text, so it needs 4.5:1 at Level AA. It also should not replace a visible label, because it disappears when the user starts typing.

Did WCAG 2.2 change the contrast rules?

No. The contrast ratios are the same as in WCAG 2.1. WCAG 2.2 added new criteria for focus visibility, target size, redundant entry and accessible authentication, and removed 4.1.1 Parsing.

Can automated tools test WCAG 2.2 compliance?

Tools such as axe-core reliably detect many issues, including contrast failures and missing labels, but they cannot judge whether labels, instructions and error messages are understandable. Combine automated tests with keyboard and screen reader checks.

How do I make form errors accessible?

Describe each error in text next to the field, link it with aria-describedby, set aria-invalid, do not rely on color alone, and move focus to a summary listing the errors with links to each field.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.