Use page.screenshot({ style: '...' }) when you need CSS only for one direct screenshot, page.addStyleTag() when a stylesheet should be inserted before capture, and stylePath with expect(page).toHaveScreenshot() for Playwright Test assertions. These options are documented as available from Playwright v1.41. The right choice depends on whether you are capturing an image or making a visual regression assertion.
This guide shows complete JavaScript and TypeScript examples, explains animation and scale differences, and includes fixes for the errors that most often make screenshot styling appear not to work.
Choose the CSS API that matches your workflow
| Workflow | Use | What it does |
|---|---|---|
| One direct screenshot | page.screenshot({ style }) |
Applies CSS text while that screenshot is being made. |
| Reusable or file-based stylesheet | page.addStyleTag({ path, content }) |
Adds a stylesheet to the page before capture. The page remains styled for later operations in that context. |
| Playwright Test visual assertion | expect(page).toHaveScreenshot({ stylePath }) |
Loads a stylesheet for the assertion and compares the resulting image with a snapshot. |
The Page API reference covers style, addStyleTag, and screenshot controls. Assertion-specific behavior is documented in PageAssertions and the visual comparisons guide.
Apply inline CSS to a direct screenshot
Pass a stylesheet string in the style property. Playwright injects it for the screenshot operation, which is useful for hiding consent banners, chat launchers, timestamps, ads, or other volatile pixels without changing your application code.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →import { chromium } from 'playwright';
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
await page.goto('https://example.com', { waitUntil: 'networkidle' });
await page.screenshot({
path: 'page.png',
style: `
.cookie-banner,
.live-chat,
[data-testid="newsletter-popup"] {
display: none !important;
}
.timestamp {
visibility: hidden !important;
}
`,
});
await browser.close();
display: none removes an element from layout; visibility: hidden keeps its space while hiding its pixels. Use the latter when removing an overlay would shift the rest of the page and make comparisons less useful. Keep selectors narrow. A selector such as div { display:none } can hide real content and make a passing snapshot meaningless.
#1 Best Overall
- 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
The style option is intended for CSS text that belongs to the capture itself. It was added in Playwright v1.41, so an older installed package can reject it as an unknown option.
Load a CSS file with page.addStyleTag
When several scripts share the same rules, keep them in a file and add that stylesheet before taking the screenshot. A relative path is resolved from the current working directory.
Create screenshot.css:
.cookie-banner,
.live-chat,
[data-testid="newsletter-popup"] {
display: none !important;
}
video,
[data-animated="true"] {
visibility: hidden !important;
}
Then inject it:
import { chromium } from 'playwright';
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com', { waitUntil: 'networkidle' });
await page.addStyleTag({ path: './screenshot.css' });
await page.screenshot({ path: 'page-with-file-css.png', fullPage: true });
await browser.close();
addStyleTag can also receive CSS in content or a stylesheet URL. Unlike screenshot-time style, this method adds a style element (or link element for a URL) to the page, so subsequent actions in the same page context see the injected rules. The method and its options are listed in the Page API.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Use stylePath for Playwright Test visual assertions
stylePath belongs to Playwright Test’s toHaveScreenshot assertion, not to the standalone Page screenshot method. It is the cleanest option when the stylesheet is part of a visual-regression test.
import { test, expect } from '@playwright/test';
import path from 'node:path';
test('home page remains visually stable', async ({ page }) => {
await page.goto('https://example.com', { waitUntil: 'networkidle' });
await expect(page).toHaveScreenshot({
stylePath: path.join(__dirname, 'screenshot.css'),
fullPage: true,
});
});
You can set stylePath on an individual assertion or share it in the expect.toHaveScreenshot configuration. The assertion waits for two consecutive screenshots to be identical before comparing the final image with the stored snapshot. That extra stabilization is why an assertion can take longer than a direct page.screenshot.
The assertion stylesheet is documented to pierce Shadow DOM and apply to inner frames. This lets a rule such as a widget-specific selector reach components that ordinary page-level selectors may not reach. Still scope selectors carefully: hiding every iframe, dialog, or button can conceal a genuine regression. The visual comparisons guide shows this technique for filtering volatile content.
Rank #2
- 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
Make the CSS deterministic
Wait for the page state you actually need
Load the page and wait for the state that your CSS expects. waitUntil: 'networkidle' can help on pages that finish loading their data through requests, but it is not a substitute for waiting on a specific component. If a popup appears after a delay, wait for its selector before hiding it or wait for the page to settle before capturing.
await page.goto('https://example.com/dashboard');
await page.waitForSelector('[data-testid="dashboard"]');
await page.waitForTimeout(300); // only when the UI has a known short transition
await page.screenshot({
path: 'dashboard.png',
style: '.toast, .live-chat { display: none !important; }',
});
Control animations and the caret
Direct Page screenshots allow animations by default. The screenshot options also control caret visibility and animation handling. For a stable direct capture, disable animations with CSS or use the documented screenshot controls in the version you have installed.
toHaveScreenshot defaults to disabling animations. Finite animations are fast-forwarded to completion; infinite animations are canceled at their initial state for the screenshot and resumed afterward. This default differs from page.screenshot, so two workflows can produce different pixels even with identical CSS.
const freezeMotion = `
*, *::before, *::after {
animation: none !important;
transition: none !important;
caret-color: transparent !important;
}
`;
await page.screenshot({
path: 'stable.png',
style: freezeMotion,
animations: 'disabled',
caret: 'hide',
});
Use CSS to freeze only the elements that must be stable when the animation itself is part of what you are testing. Disabling every transition is appropriate for a deterministic baseline, but not for a test whose purpose is to verify motion.
Choose a scale deliberately
scale: 'css' produces one output pixel per CSS pixel. scale: 'device' uses device pixels and can create substantially larger files on high-DPI screens. Use CSS scale for compact, cross-machine baselines; use device scale when the test specifically represents a physical high-density display.
await page.screenshot({
path: 'css-pixel-baseline.png',
scale: 'css',
fullPage: true,
style: freezeMotion,
});
Target the right elements
Hide without shifting layout
Overlays such as consent dialogs and chat buttons generally should use display: none !important. For dynamic text that changes width but must retain the same layout, use visibility: hidden !important or mask the text with a fixed-size replacement. Avoid changing margins, widths, or font sizes merely to hide volatile content; those changes can move neighboring elements and create unrelated diffs.
Rank #3
- 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.
Deal with specificity and inline styles
Application CSS may use inline declarations or highly specific selectors. Add !important only to the declarations that must win, and inspect the element in a headed run if a rule appears ineffective. Confirm that the selector matches the rendered state, not a pre-hydration placeholder.
Shadow DOM and frames
For toHaveScreenshot, the assertion stylesheet reaches Shadow DOM and inner frames as documented. For a direct screenshot, style the owning document or component explicitly; a selector in the top-level document cannot automatically cross an unrelated frame boundary. If a frame is under your control, inject its own stylesheet or style a stable host element instead of hiding the entire frame.
Combine styling with capture options
CSS filtering works with the other Page screenshot options. For long pages, use fullPage: true. For a particular region, use a locator screenshot or a clip rectangle. Select PNG, JPEG, or another supported format according to whether you need lossless pixels or a smaller artifact.
Recommended Free Tools
const article = page.locator('main article');
await article.screenshot({
path: 'article.webp',
type: 'webp',
style: `
.share-tools, .recommended-reading { display: none !important; }
`,
});
Keep the capture boundary and the CSS purpose aligned. A rule that removes an element outside the clipped region has no practical effect, while a broad rule can alter layout inside it.
Common failures and fixes
“Unknown option: style”
Check the installed Playwright version. The Page API documents style as added in v1.41. Upgrade the package used by the running script, not only a globally installed command, then verify the lockfile and browser binaries are in sync.
The file stylesheet cannot be found
addStyleTag({ path }) resolves relative paths from the current working directory. Log process.cwd(), use an absolute path built with path.resolve, or place the CSS next to the script and reference that location explicitly.
Rank #4
- 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
stylePath is rejected or expect is undefined
stylePath is a Playwright Test assertion option. Run the test with @playwright/test and call expect(page).toHaveScreenshot(). In a standalone automation script, use page.screenshot({ style }) or addStyleTag instead.
The rule matches nothing
Inspect the rendered DOM and verify timing. The element may be inside Shadow DOM, an inner frame, or a state that has not appeared yet. Use a stable data attribute where possible, wait for the state, and avoid selectors based on generated class names.
The screenshot still changes between runs
Look beyond CSS: dates, randomized content, network responses, fonts, viewport size, animation defaults, caret state, and device scale can all change pixels. Freeze only the volatile sources you have identified, set a fixed viewport and scale, and use the assertion’s built-in stabilization rather than adding arbitrary long delays.
Too much content disappears
Temporarily remove !important, test each selector separately, and narrow a descendant selector to the exact component. A passing visual assertion is not useful if the stylesheet hides the feature under test.
Performance, reliability, and maintenance
Small targeted rules add little overhead; very broad selectors and large injected stylesheets increase style recalculation and make failures harder to diagnose. Keep a dedicated screenshot stylesheet rather than copying production CSS, and document why each volatile selector is hidden. Review it whenever the page layout changes.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →For reliable baselines, pin the viewport, browser project, color scheme, locale, and scale in your Playwright configuration. Treat the screenshot stylesheet as test code: review changes, keep selectors semantic, and never use it to hide a component whose appearance is the subject of the test.
Best Value
- 【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.
Or skip the browser setup
If you only need a clean image or PDF from a URL, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.
One request is enough:
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 options such as full-page capture, CSS selectors, custom CSS and JavaScript, device presets, dark mode, PDF output, blocking, cookies, headers, caching, signed links, asynchronous jobs, bulk capture, and usage reporting.
The same request from Python:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
And from Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', data));
ScreenshotNeo also includes an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots, and every feature is included on every plan. Create a free ScreenshotNeo account.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsFrequently Asked Questions
Can I keep the same screenshot CSS for both a script and a test?
Yes. Store the rules in one CSS file, load it with page.addStyleTag({ path }) in a direct-capture script, and reference the same file with stylePath in a Playwright Test assertion. Keep the file’s selectors limited to capture-only behavior.
Why can a visual assertion take longer than my direct screenshot?
toHaveScreenshot waits for two consecutive identical screenshots before comparison and then performs the snapshot assertion. A direct page.screenshot returns after its capture conditions are met, so it normally has less stabilization work.
Should I commit the generated screenshot stylesheet?
Treat it as part of the test suite and commit it when it defines an intentional, reviewable baseline. Include comments or naming that explain each hidden volatile element, and review the file whenever the UI changes.
Quick Recap
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.

