Skip to content
Tutorials Center
My learning

Topics

Lesson 124 of 139 ยท Best Practices

Linting and Visual Regression for CSS

Catch CSS bugs automatically: configure Stylelint, add screenshot-based visual regression tests, and check color contrast in code before users find the problems.

CSS fails quietly. A typo in a property name is ignored, an unmatched selector does nothing, and a change to a shared class can break a page nobody opened. Nothing throws an error, so mistakes ship. The remedy is the same as in any other language: automate the checks.

Three kinds of automation fit CSS well. A linter reads the source and flags mistakes and style violations. Visual regression tests compare screenshots against approved ones and flag unexpected changes. Contrast checks verify the one thing that is easy to measure and expensive to get wrong, readable text. This lesson covers all three, with examples you can run here and configuration you can copy into a project.

Linting with Stylelint

Stylelint is the standard CSS linter. It parses your stylesheets (including .scss and CSS inside HTML or components with the right syntax plugin) and reports problems with a rule name and a position. Install it as a dev dependency and give it a config file:

Terminal
npm install --save-dev stylelint stylelint-config-standard
JSON
{
  "extends": ["stylelint-config-standard"],
  "rules": {
    "declaration-no-important": true,
    "selector-max-id": 0,
    "selector-max-specificity": "0,3,0",
    "color-named": "never",
    "unit-disallowed-list": ["pt"]
  }
}

Save that as .stylelintrc.json, then run npx stylelint "src/**/*.css". Add --fix to let it repair what it can automatically, such as spacing and shorthand.

The rules fall into two families, and it helps to treat them differently:

Family Examples Why
Possible errors property-no-unknown, declaration-block-no-duplicate-properties, color-no-invalid-hex, no-duplicate-selectors, block-no-empty Catch real bugs. Always on.
Conventions selector-class-pattern, declaration-no-important, selector-max-specificity Enforce team decisions. Tune to your architecture.

Pure formatting rules (indentation, quotes) are better left to a formatter such as Prettier, so the linter focuses on correctness and design.

Enforcing your architecture

The convention rules are where a linter earns its keep. If your team uses BEM (see CSS Architecture), you can encode it:

JSON
{
  "rules": {
    "selector-class-pattern": [
      "^[a-z][a-z0-9]*(-[a-z0-9]+)*(__[a-z0-9]+(-[a-z0-9]+)*)?(--[a-z0-9]+(-[a-z0-9]+)*)?$",
      { "message": "Use BEM names such as card, card__title or card--featured." }
    ],
    "custom-property-pattern": "^(color|space|font)-[a-z0-9-]+$"
  }
}

Now a class named CardTitle or a variable named --blue fails the build with a message explaining the convention, instead of a reviewer repeating it in every pull request. Two good habits: start with the standard config and add rules one at a time, and when a rule has a legitimate exception, disable it on that line with a comment, never globally:

CSS
/* stylelint-disable-next-line declaration-no-important */
.sr-only { position: absolute !important; }

Run the linter in three places: in your editor (so you see problems while typing), in a pre-commit hook, and in CI (so nothing merges without passing). Only the CI run is a guarantee.

How a rule works

A lint rule is a small program: parse the CSS into a tree, walk it, and report nodes that match a pattern. You can feel how simple that is with a miniature version. The checker below applies three rules to the text in the box, reports line numbers, and is nothing more than regular expressions over lines. Real Stylelint uses a proper parser, which is why you should use it rather than this toy.

A toy CSS linter

The output lists one problem per line: line 1 uses !important, line 2 uses an ID, and line 3 misspells color. Edit the text and press Lint to see it react.

Visual regression testing

A linter reads code. It cannot tell you that a change made the header overlap the logo. Visual regression testing closes that gap: a tool opens your pages in a real browser, takes screenshots and compares them pixel by pixel against baseline images that a human approved earlier. A difference fails the test and produces an image showing exactly what moved.

flowchart LR
  A["Change CSS"] --> B["Render pages in a browser"]
  B --> C["Screenshot"]
  C --> D{"Same as baseline?"}
  D -- yes --> E["Test passes"]
  D -- no --> F["Diff image, review"]
  F -- "intended" --> G["Update baseline"]
  F -- "bug" --> A

A failing screenshot is a question: bug, or intended change? Only a human can answer, and answering "intended" replaces the baseline.

Playwright has this built in. A test looks like this:

JavaScript
import { test, expect } from "@playwright/test";

test("pricing page looks right", async ({ page }) => {
  await page.goto("/pricing");
  await expect(page).toHaveScreenshot("pricing.png", {
    fullPage: true,
    animations: "disabled",
    maxDiffPixelRatio: 0.002,
  });
});

The first run saves pricing.png as the baseline. Later runs compare against it. npx playwright test --update-snapshots accepts new baselines after you have reviewed the diffs. Hosted services (Chromatic, Percy and similar) add side-by-side review screens and approval workflows on top of the same idea.

Making screenshots stable

The hard part is not taking screenshots, it is making them deterministic. A test that fails randomly gets ignored, which is worse than no test. Remove every source of variation:

  • Same environment. Fonts and anti-aliasing differ between operating systems. Generate baselines in the same container image that CI uses, not on your laptop.
  • Disable animation. Use animations: "disabled", or in your own CSS @media (prefers-reduced-motion: reduce) rules that remove transitions (see Accessibility).
  • Fix the data. Mock the API, freeze the clock, and replace images that change. A date banner that says "Today" breaks tomorrow.
  • Wait for fonts and images. Capture only after loading completes.
  • Mask what must vary. Pass mask: [page.locator(".ad-slot")] to paint over regions that change.
  • Pin the viewport. Test the widths where your media queries change layout, such as 375, 768 and 1280.

Test components in isolation as well as pages. A screenshot of one button in all its states (default, hover, focus, disabled) fails with a tiny, easy-to-read diff, while a full-page screenshot fails on any change anywhere.

What a diff really is

Under the hood a comparison is simple: walk both images pixel by pixel and count the pixels that differ by more than a small tolerance. This demo draws two small canvases from code, one with a slightly shifted button, and runs that comparison. Real tools add anti-aliasing detection, but the principle is the same.

Comparing two renders pixel by pixel

The red areas in the third canvas are where the two renders disagree. A threshold such as maxDiffPixelRatio decides how much disagreement you tolerate.

Checking contrast automatically

Color contrast is the most common accessibility failure, and the rule is mathematical: WCAG defines a contrast ratio between two colors from 1:1 to 21:1. Body text needs at least 4.5:1, large text (roughly 24px, or 19px bold) needs 3:1, and UI components and graphics need 3:1. Accessibility explains the targets.

You can test this in three layers:

  1. While designing. Check token pairs once, in code or in your browser's dev tools (DevTools). If you keep colors in custom properties, you only need to test each foreground/background pair, not each page.
  2. In unit tests. A tiny function can assert that every text/background pair in your design tokens passes. The calculator below shows the formula.
  3. In end-to-end tests. Run axe-core (the @axe-core/playwright package) on rendered pages. It checks contrast of actual text on actual backgrounds and reports the failing elements. Automated tools find roughly a third of accessibility problems, so they supplement manual review and keyboard testing, they do not replace them.
A WCAG contrast checker

With the default colors the ratio is 6.29:1, a pass. Try #aaaaaa on white, which scores 2.32:1 and is the classic failing "subtle gray", then #767676, which is the lightest gray on white that still reaches 4.54:1.

Putting it together in CI

A reasonable pipeline for a CSS-heavy project runs the cheap checks first:

YAML
jobs:
  css:
    steps:
      - run: npm ci
      - run: npx stylelint "src/**/*.css"
      - run: npx playwright install --with-deps chromium
      - run: npx playwright test

Stylelint finishes in seconds and catches typos and convention breaks. The Playwright run is slower and checks the rendered result, including axe contrast scans if you add them. Store the diff images as build artifacts so reviewers can see what changed without reproducing it locally.

Do not try to test everything. Pick the pages and components where a broken layout would hurt most: the home page, checkout, your shared button and form components. A small suite that people trust beats a huge one they re-baseline without looking.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which problem can a CSS linter catch but a visual regression test cannot reliably catch?

    A linter reads source code, so it flags unknown properties anywhere, even in states or pages no screenshot covers. Visual tests only see what is rendered.
  2. 2. A visual regression test fails after an intended redesign. What should you do?

    A failing diff is a question for a human. If the change is intended, approve it by updating the baseline. Raising thresholds just hides real bugs.
  3. 3. Which practice makes screenshot tests less flaky?

    Flakiness comes from variation. Remove it: the same fonts and browser, no motion, and fixed content.
  4. 4. What contrast ratio does WCAG AA require for normal body text?

    4.5:1 is the AA minimum for normal text. Large text and UI components need 3:1. 21:1 is the maximum, black on white.

Summary

  • Stylelint flags real bugs (unknown properties, duplicates, invalid colors) and can enforce your architecture, such as BEM class patterns and a specificity cap.
  • Run it in the editor, a pre-commit hook and CI; leave pure formatting to a formatter.
  • Visual regression tests compare screenshots against approved baselines; a diff is a question for a human, and "intended" means updating the baseline.
  • Make screenshots deterministic: one environment, no animation, fixed data, masked dynamic regions, pinned viewports.
  • Check contrast by pairs of design tokens and with axe-core on rendered pages, and remember automated tools complement manual accessibility testing.

Next: Project: Profile Card.