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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Set a screenshot-only background with Playwright’s style option: await page.screenshot({ path: 'shot.png', style: 'html, body { background: #1e293b !important; }' });. For a persistent change, inject the same CSS with page.addStyleTag() before capturing. Use omitBackground: true only when you want transparency, not a solid color.

Choose the result you need

Goal Playwright setting Output
Change color only for one capture style Temporary CSS applied during the screenshot
Keep the color for several actions or captures page.addStyleTag() CSS remains in the page until navigation or removal
Capture a transparent image omitBackground: true PNG with transparent areas instead of Playwright’s default white
Print a colored PDF printBackground: true and print-media handling PDF that includes background graphics when the page’s print CSS allows them

Apply a color for one screenshot

The style option is the cleanest approach for a one-off image. It applies a stylesheet while the screenshot is made, so your application’s normal CSS is not permanently changed. The rule below targets both the document root and the body; !important helps it win against site styles that set a white background.

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: 'dark-background.png',
  style: 'html, body { background: #1e293b !important; }'
});

await browser.close();

Replace #1e293b with any valid CSS color, such as rgb(15 23 42), hsl(220 40% 10%), or a named color. The stylesheet can also set gradients, background images, or other capture-only adjustments. Playwright documents that screenshot styling can pierce Shadow DOM and apply to inner frames, which is useful when the visible background is rendered inside a component or embedded frame.

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

Make a full-page background cover the document

A viewport screenshot captures only what is visible. Add fullPage: true when the background must extend through the entire scrollable page.

#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • 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
await page.screenshot({
  path: 'full-page.png',
  fullPage: true,
  style: 'html, body { background: #0f172a !important; }'
});

Full-page capture can trigger additional layout and lazy-loading work. Wait for important content before taking the image, and use a deterministic viewport and device scale factor in visual tests.

Color only one component

Use a locator screenshot when the page should remain unchanged and only a component needs a colored background.

await page.locator('.hero').screenshot({
  path: 'hero.png',
  style: '.hero { background: #1e293b !important; }'
});

If the component has a transparent child over the page, style the element that actually paints the pixels. Inspect the DOM to determine whether that is the host, a wrapper, or a pseudo-element.

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

Inject CSS when the change should persist

addStyleTag inserts a stylesheet into the page before capture. This is useful when you need the same override for several screenshots, interactions, or assertions.

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 { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });

await page.addStyleTag({
  content: `
    html, body {
      background: #1e293b !important;
    }
  `
});

await page.screenshot({ path: 'persistent-override.png', fullPage: true });
await browser.close();

Because this stylesheet remains active, later interactions and screenshots see the override. If you need to remove it, keep the returned style element handle and call its removal method, or navigate to a new document. A navigation replaces the document and therefore removes injected styles.

Handle pages that paint a nested surface

A white screenshot can come from a wrapper such as #app, a card, or a pseudo-element rather than body. Extend the rule to the elements that cover the viewport:

await page.screenshot({
  path: 'surface.png',
  style: `
    html, body, #app, .page-shell {
      background: #111827 !important;
    }
  `
});

For a pseudo-element, override it explicitly, for example .page-shell::before { background: #111827 !important; }. Avoid broad rules that recolor text panels or controls unless that is intentional.

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

Solid colors versus transparent screenshots

Playwright’s omitBackground: true does not choose a color. It hides the default white background and allows transparency, as stated in the Playwright API documentation. Use a format that supports an alpha channel, normally PNG.

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 page.screenshot({
  path: 'transparent.png',
  omitBackground: true
});

Do not combine an opaque CSS background with omitBackground: true when transparency is the goal: your CSS rule still paints an opaque surface. The option is not applicable to JPEG, whose format has no alpha channel. WebP can support transparency when encoded in a configuration that preserves alpha, but PNG is the least ambiguous choice for test fixtures and design assets.

Transparent element capture

await page.locator('.logo').screenshot({
  path: 'logo-transparent.png',
  omitBackground: true
});

Only pixels that are actually transparent remain transparent. A child element with its own solid background will remain opaque.

Why a Playwright screenshot is still white

  • The rule loses the cascade: add !important, target the painted wrapper, or load the override after the site stylesheet.
  • The screenshot is transparent by design: check whether omitBackground is enabled and inspect the image against a checkerboard viewer.
  • Only the viewport was captured: use fullPage: true for the complete document.
  • A component or iframe owns the background: target its host or inner content. The style screenshot option can reach Shadow DOM and inner frames, while a normal page stylesheet may not cross those boundaries.
  • Images or fonts have not loaded: wait for a selector, a load state, or application-specific readiness signal before capture.
  • Animation changes the color: disable transitions and animations in the temporary stylesheet for deterministic output.
await page.screenshot({
  path: 'stable.png',
  style: `
    *, *::before, *::after {
      animation: none !important;
      transition: none !important;
    }
    html, body { background: #1e293b !important; }
  `
});

Background colors in PDFs

page.pdf() uses print CSS media by default. Background graphics are controlled by printBackground, so a color visible in a screen screenshot may disappear from the PDF.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.emulateMedia({ media: 'screen' });
await page.pdf({
  path: 'colored.pdf',
  printBackground: true
});

Use emulateMedia({ media: 'screen' }) when you want screen styles rather than @media print rules. If print CSS intentionally changes the color, inspect those rules. For exact color reproduction, the documented -webkit-print-color-adjust property can force the browser to preserve author colors:

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • 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
await page.addStyleTag({
  content: `
    html, body {
      background: #1e293b !important;
      -webkit-print-color-adjust: exact !important;
      print-color-adjust: exact !important;
    }
  `
});
await page.pdf({ path: 'exact-color.pdf', printBackground: true });

PDF pagination is separate from screenshot sizing. Use PDF paper size, margins, orientation, and page ranges for document layout; do not expect fullPage screenshot options to affect PDF output.

Use the same styling in visual regression tests

Screenshot assertions support a stylesheet through stylePath. Keep the override in version control so the baseline and comparison receive identical CSS.

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

test('dark background is stable', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page).toHaveScreenshot('dark-bg.png', {
    stylePath: './screenshot-overrides.css'
  });
});

screenshot-overrides.css might contain:

html, body {
  background: #1e293b !important;
}

*, *::before, *::after {
  animation: none !important;
  transition: none !important;
}

Use omitBackground in the assertion only when the expected image is intentionally transparent. Keep browser version, viewport, fonts, and device scale consistent to avoid unrelated pixel differences.

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

A practical troubleshooting checklist

  1. Confirm the intended output: opaque color, transparent PNG, component crop, full page, or PDF.
  2. Identify which element paints the pixels by inspecting computed styles and overlays.
  3. Apply a capture-only style first; switch to addStyleTag only when persistence is needed.
  4. Wait for the page’s meaningful ready state, not merely a fixed delay, when content loads asynchronously.
  5. For PDFs, select the correct media type and enable printBackground.
  6. Open the generated file in an image viewer that shows alpha correctly; white in a viewer does not prove the file is opaque.
  7. When tests are flaky, freeze animation, use stable data, and keep the override file identical across baseline and comparison runs.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server when you prefer an HTTP request over maintaining Playwright browser code. A single GET request returns PNG, JPEG, WebP, or PDF. The API can apply custom CSS, wait for selectors or network idle, capture full pages or one CSS-selected element, set viewport and device presets, emulate dark mode, and more.

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.
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 documentation for all parameters, including a background override and transparent output. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers report the page verdict and whether the request was billed. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Equivalent requests from Python and Node.js

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)

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 fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

Use a short-lived API key where possible, keep it out of browser-side code, and set a request timeout appropriate for the target site. For large batches, ScreenshotNeo supports up to 100 URLs per call, asynchronous jobs with signed webhooks, caching with a chosen TTL, and a usage API.

Frequently Asked Questions

Can I set a different background for each screenshot?

Yes. Pass a different CSS string to each screenshot’s style option, or inject and replace a stylesheet between captures.

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

Does omitBackground work with JPEG?

No. JPEG does not support an alpha channel; use PNG when transparent pixels are required.

Why does my page background work in a PNG but not a PDF?

PDF generation uses print media by default. Emulate screen media when appropriate and set printBackground: true; also check @media print rules.

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.