October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

How to Make Website Screenshot Tests Stable When the Page Resizes

Make responsive screenshot tests more reliable by controlling viewport timing, page state, animation, screenshot scale, and baseline environment.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For stable responsive screenshot tests, set the intended viewport before navigation, wait for the page state your test cares about, and compare with Playwright’s toHaveScreenshot() in the same browser and operating-system environment used to create the baseline. Treat a deliberate resize after navigation as a separate test of resize behavior—not as an interchangeable way to establish the initial layout.

Why resizing can make screenshot tests fail

A viewport change can alter responsive layout, and it can also change the conditions under which a page loads and renders. A visual diff may therefore signal a real layout regression, a different initial page state, unsettled content, or a changed rendering environment. The goal is to control incidental variation without hiding the responsive behavior the test is meant to catch.

As an Amazon Associate I earn from qualifying purchases.

Playwright notes that rendering can vary with the host operating system, browser version and settings, hardware, power source, headless mode, and other factors. Its guidance is to run comparisons in the same environment used to generate the expected screenshots. Playwright: Visual comparisons.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set the viewport before navigation for initial-layout tests

When the test asks how a page loads at a particular size, set that size before calling page.goto(). Playwright cautions that many sites do not expect phones to change size and recommends setting viewport size before navigation. Playwright Page API: setViewportSize().

#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB | 1920×1080 LED Monitor, 4ms GtG, Adaptive Sync, HDMI 1.4, Tilt Adjust, Low Blue Light, 4yr Advance Replacement Warranty
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Choose explicit dimensions that reflect the responsive behavior your product supports. Include sizes around meaningful layout breakpoints as well as representative narrow and wide layouts; there is no universal breakpoint list or required number of viewport targets. Keep the dimensions consistent between baseline creation and later runs.

Playwright Test example: load directly at the target size

This example tests a page loaded at a 390-by-844 CSS-pixel viewport. Replace the URL and dimensions with the route and sizes relevant to your application.

import { test, expect } from '@playwright/test';

test('mobile layout at initial load', async ({ page }) => {
  await page.setViewportSize({ width: 390, height: 844 });
  await page.goto('https://example.com');

  // Wait for the application state this screenshot is intended to cover.
  await expect(page.getByRole('main')).toBeVisible();
  await expect(page).toHaveScreenshot('home-mobile.png');
});

The viewport dimensions here are an example, not a Playwright recommendation. Select values based on your own supported layouts and responsive breakpoints.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test resize transitions separately

If the behavior under test is what happens when an already loaded page changes size, navigate first, then resize deliberately and assert the resulting layout. That tests a live resize transition; it should not be confused with a baseline captured after loading directly at the target viewport.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
import { test, expect } from '@playwright/test';

test('navigation adapts after a live resize', async ({ page }) => {
  await page.setViewportSize({ width: 1280, height: 800 });
  await page.goto('https://example.com');

  await page.setViewportSize({ width: 390, height: 844 });
  await expect(page.getByRole('button', { name: 'Open menu' })).toBeVisible();
  await expect(page).toHaveScreenshot('home-after-resize.png');
});

Use selectors and expected states that match the page. If the application updates asynchronously in response to resizing, wait for the relevant state rather than relying on an arbitrary delay alone.

Use screenshot assertions and control only relevant variation

Playwright Test’s toHaveScreenshot() assertion waits until two consecutive screenshots are identical before comparing the latest image to its expectation. Its default animation behavior is disabled. Finite animations are fast-forwarded, while infinite animations are canceled for capture and then resumed. This helps with motion-related instability, but it does not freeze backend data or guarantee that every source of dynamic content has stopped changing. Playwright: Visual comparisons.

Wait for the application state that matters, such as a key element becoming visible or loaded data appearing, then make the screenshot assertion. Avoid treating the two-identical-screenshots check as a substitute for setting up deterministic application state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Mask or restyle narrowly scoped volatile regions

If a timestamp, rotating promotion, or unrelated live widget is outside the test’s purpose, mask it or apply screenshot-specific styling. Keep the region under test visible: hiding responsive navigation, text wrapping, image placement, or container edges would conceal the very regressions the test should find.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.
await expect(page).toHaveScreenshot('home-mobile.png', {
  mask: [page.locator('[data-testid="live-clock"]')],
});

Playwright also supports screenshot-specific styles and comparison settings through the screenshot assertion API. Visual comparison options.

Keep device, screen, scale, and comparison settings consistent

Use device emulation when device properties matter

A viewport alone may not represent the behavior you intend to test. Use Playwright device emulation when user agent, screen size, or touch behavior is part of the scenario. Playwright: Emulation. For example, a configured device can be applied through the test configuration:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  projects: [
    {
      name: 'mobile-chromium',
      use: { ...devices['Pixel 7'] },
    },
  ],
});

Device presets and their available names depend on the installed Playwright version. If your test needs to control screen and viewport independently, Playwright points to the browser context’s screen and viewport options; setViewportSize() also resets screen size. Page API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose viewport or full-page capture intentionally

A viewport screenshot and a full-page screenshot test different things. Full-page capture includes the scrollable page and can be affected by changes in document height or lazy-loaded content. Choose it when the complete page is the intended subject; otherwise capture the viewport. Playwright documents the fullPage option, but does not prescribe a universal strategy for lazy loading. Playwright Page API: screenshots.

Rank #4
Sale
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor | 100Hz, Game Mode, Advanced Eye Comfort, HDMI and D-sub Ports (LS27D366GANXZA)
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Keep screenshot scale fixed

Playwright supports CSS-pixel scale, which produces one image pixel per CSS pixel, and device-pixel scale, which can produce larger images on high-DPI devices. Use the same scale for baseline and comparison so image dimensions and detail remain comparable. Page screenshot API.

Use comparison tolerances sparingly

Options such as maxDiffPixels can permit small differences, but a broad tolerance can also hide an actual layout change. Start with the default comparison behavior; if you have a known, acceptable source of pixel variation, choose a narrowly scoped tolerance and review whether it still catches the layout changes your test is intended to detect. The API exposes the option but does not set a universal best value. Playwright: toHaveScreenshot().

Separate baselines by browser and environment

Generate and compare snapshots under matching browser and operating-system conditions wherever practical. If your test matrix intentionally covers multiple browsers or platforms, keep expectations associated with those projects rather than treating their pixel output as interchangeable. Record relevant configuration consistently, including browser, viewport, scale, and headless mode. Playwright’s visual comparison guidance explains why host and browser conditions affect rendering. Visual comparisons.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Review snapshot changes before updating baselines

When a comparison fails, inspect the diff first. Confirm the viewport, page state, and rendering environment, then decide whether the changed output is an intended product change. Playwright supports updating snapshots with --update-snapshots; use it after review, not automatically to silence a failure. Updating screenshots.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Troubleshoot common resize-related failures

  • The page looks like the wrong responsive layout: For an initial-load test, set the viewport before goto(). Confirm the configured dimensions and that the test is not accidentally using a different device project.
  • The page changes after the screenshot: Wait for the application state relevant to the capture. The screenshot assertion’s stability check does not stop changing backend data, rotating content, or other application behavior.
  • Only a live resize test fails: Check that the test intentionally starts at one size, resizes after navigation, and asserts the expected post-resize state. Do not use this flow to stand in for a direct-load baseline.
  • Differences appear across machines or CI: Compare browser version, operating system, headless setting, and other relevant environment settings. Generate and compare baselines in matching conditions.
  • Image dimensions differ unexpectedly: Verify viewport dimensions, full-page versus viewport capture, and screenshot scale. These settings change what is captured or the resulting image size.
  • A tolerance hides a meaningful change: Reduce or remove the tolerance and review the diff. A threshold should account only for known minor variation, not cover layout movement that matters.
  • A baseline update makes the test pass but the result is unclear: Revert or defer the update until the image change is understood and approved; update snapshots only for intentional changes.

Or skip the browser setup

If you need a screenshot without configuring a browser test, ScreenshotNeo returns a screenshot or PDF from one GET request. For example, save a WebP capture of the page:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. ScreenshotNeo can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000.

Sign up free for ScreenshotNeo to get 1,000 screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Does Playwright guarantee that a page is stable after two matching screenshots?

No. The assertion waits for two consecutive identical captures, but changing application or backend state can still affect later output.

Is there a universal viewport size or pixel-difference threshold for responsive tests?

No. Choose viewport targets based on your product’s supported responsive behavior, and set any tolerance narrowly for known acceptable variation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.