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

Set a Playwright viewport with the API that matches your scope: page.setViewportSize({ width, height }) for one page, browser.newContext({ viewport: { width, height } }) for every page in a context, or use.viewport/test.use() in Playwright Test. Width and height are CSS pixels. For repeatable tests, choose explicit dimensions rather than null.

The safest default is to establish the viewport before navigation, especially when testing a phone-sized layout. The browser context default is 1280×720 when you do not provide a viewport.

Choose the right viewport scope

Viewport configuration is hierarchical. Pick the narrowest scope that expresses your intent; a shared context or test configuration prevents accidental differences between pages.

Need Use What it affects
Resize one page, including during a test page.setViewportSize({ width, height }) That page only; the call also resets its emulated screen size.
Give all pages in a context the same dimensions browser.newContext({ viewport: { width, height } }) Every page created by that context.
Apply a standard size to tests or a project use.viewport or test.use() Playwright Test projects, files, describe blocks, or individual tests.
Emulate a named phone or desktop ...devices['Device name'] Viewport plus user agent, touch capability, screen characteristics, and other device settings.
Record a script at a fixed size npx playwright codegen --viewport-size="W,H" URL The code generator’s browser window.

Set a viewport on one page

Use the Page API when only one page needs a different layout, or when a test intentionally changes size partway through.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.setViewportSize({ width: 640, height: 480 });
await page.goto('https://example.com');

console.log(await page.title());
await browser.close();

Put setViewportSize before goto whenever the initial responsive state matters. Many sites do not expect a phone-sized page to change after loading; navigating at the final dimensions lets CSS, JavaScript, and responsive breakpoints initialize consistently.

Resize an existing page

await page.goto('https://example.com');
await page.setViewportSize({ width: 1440, height: 900 });
// Future layout and screenshots use the new viewport.

Changing the viewport does not recreate the page or context. It changes the page dimensions and resets the emulated screen size. If your test needs independent control of window.screen, configure both viewport and screen when creating the context instead.

Set a context default

A browser context is the practical choice for a suite that opens several pages with one consistent viewport. Supply the option to browser.newContext() before creating any pages.

import { chromium } from 'playwright';

const browser = await chromium.launch();
const context = await browser.newContext({
  viewport: { width: 1280, height: 1024 },
});

const page = await context.newPage();
await page.goto('https://example.com');
const secondPage = await context.newPage();
await secondPage.goto('https://example.com/pricing');

await context.close();
await browser.close();

If no viewport is supplied, Playwright documents a 1280×720 default. Explicit values make the test’s rendering independent of the machine running it.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Control screen dimensions separately

viewport controls the page’s layout viewport. The context’s screen option emulates window.screen and is used when a viewport is set.

const context = await browser.newContext({
  viewport: { width: 1280, height: 800 },
  screen: { width: 1440, height: 900 },
});

Use this distinction only when application code reads screen properties. For ordinary responsive testing, a viewport alone is simpler and less error-prone.

Configure Playwright Test

When many tests share dimensions, put the setting in the test runner rather than repeating page setup.

Global or project-level configuration

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

export default defineConfig({
  use: {
    viewport: { width: 1280, height: 720 },
  },
});

For separate desktop and mobile runs, define projects with different use.viewport values. This keeps each worker’s environment consistent and makes the chosen dimensions visible in the configuration.

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

Override a file, describe block, or test

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

test.use({ viewport: { width: 1600, height: 1200 } });

test('wide layout', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page.locator('nav')).toBeVisible();
});

test.describe('tablet checks', () => {
  test.use({ viewport: { width: 1024, height: 768 } });

  test('tablet layout', async ({ page }) => {
    await page.goto('https://example.com');
  });
});

test.use() can scope settings to the remaining tests in a file or to a describe block. Keep the dimensions near the tests that need them so a later change does not silently alter unrelated coverage.

Combine a custom viewport with a device preset

A device descriptor is more than a width and height. It can include a mobile user agent, screen size, touch support, and other emulation behavior. Use one when those characteristics affect the code under test; use a custom viewport when dimensions are the only variable.

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

export default defineConfig({
  projects: [
    {
      name: 'chromium-custom-width',
      use: {
        ...devices['Desktop Chrome'],
        viewport: { width: 1280, height: 720 },
      },
    },
  ],
});

The order matters: put your explicit viewport after the spread. The device descriptor contains its own viewport, so placing your value first would allow the preset to overwrite it.

Viewport dimensions alone do not turn a desktop browser into a real handset. Full device emulation has browser-specific limits; for example, the Browser API documents that isMobile is not supported in Firefox.

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

Set device scale factor when pixel density matters

Viewport width and height are CSS-pixel dimensions. A separate deviceScaleFactor controls the emulated device pixel ratio, which affects rasterization and screenshots without changing the CSS viewport.

const context = await browser.newContext({
  viewport: { width: 2560, height: 1440 },
  deviceScaleFactor: 2,
});

Use this for high-DPI rendering checks or when an image comparison must represent a particular pixel density. Do not use scale factor as a substitute for changing responsive breakpoints.

Use a fixed size with codegen

To record interactions at a chosen viewport, pass width and height as a comma-separated value:

npx playwright codegen --viewport-size="800,600" https://playwright.dev

If you need the broader behavior of a named device while recording, use codegen’s --device option instead of only setting dimensions.

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

Build a repeatable viewport matrix

Responsive bugs usually appear at breakpoints rather than at one arbitrary size. Define a small, intentional matrix and run the same assertions at each size.

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

const viewports = [
  { name: 'phone', width: 390, height: 844 },
  { name: 'tablet', width: 768, height: 1024 },
  { name: 'desktop', width: 1440, height: 900 },
];

for (const viewport of viewports) {
  test(`${viewport.name} navigation`, async ({ browser }) => {
    const context = await browser.newContext({
      viewport: { width: viewport.width, height: viewport.height },
    });
    const page = await context.newPage();
    await page.goto('https://example.com');
    await expect(page.locator('body')).toBeVisible();
    await context.close();
  });
}

Keep the list small enough to run on every change, and add dimensions only when they represent a product breakpoint or a known failure. Reusing a context for pages that share a size avoids repeated setup; create separate contexts when isolation or different emulation is required.

Why viewport: null is usually the wrong choice

Setting viewport: null opts out of consistent viewport emulation and lets the host window determine the size. The documented result is nondeterministic test execution: a laptop, CI worker, and headed browser can render different layouts.

Use explicit width and height for visual assertions, responsive branching, and screenshot comparison. Reserve null for a deliberate test of host-window behavior, and record the environment if you choose it.

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

Verify what the page actually sees

When a layout assertion fails, print the values exposed to page scripts before changing configuration.

const dimensions = await page.evaluate(() => ({
  innerWidth: window.innerWidth,
  innerHeight: window.innerHeight,
  screenWidth: window.screen.width,
  screenHeight: window.screen.height,
  devicePixelRatio: window.devicePixelRatio,
}));

console.log(dimensions);

innerWidth and innerHeight show the CSS viewport. The screen values reveal whether a separate screen option or a device preset is influencing the page, and devicePixelRatio confirms scale-factor behavior.

Troubleshooting viewport problems

The first render uses the wrong breakpoint

Cause: the page was navigated before the final viewport was applied.

Fix: set the viewport in newContext, in Playwright Test configuration, or call setViewportSize before goto. If you resize after navigation intentionally, wait for the responsive UI to settle before asserting.

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.

My explicit size is ignored when using a device

Cause: the device descriptor was spread after your custom value.

Fix: spread the descriptor first and put viewport: { width, height } afterward.

Assertions pass locally but fail in CI

Cause: a missing viewport or viewport: null allows the host window to decide the dimensions.

Fix: define explicit dimensions in the context or use configuration, and log the evaluated dimensions when diagnosing a failure.

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

CSS responds correctly but JavaScript reads unexpected screen values

Cause: viewport and screen are separate emulated properties.

Fix: provide a context-level screen value when the application depends on window.screen. A later page resize also resets screen size.

A phone test behaves like desktop

Cause: only the viewport was changed; user agent, touch, and other device behavior remain desktop-like.

Fix: start from an appropriate devices preset and override its viewport only if you need nonstandard dimensions. Check browser support for each emulation option.

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

Screenshots have the wrong pixel density

Cause: CSS dimensions were correct but the device scale factor was not.

Fix: set deviceScaleFactor at context creation and keep it separate from viewport width and height.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean image or PDF of a URL rather than an interactive Playwright test, ScreenshotNeo provides a single GET request. It can capture a full page, load lazy images, select one element, apply a viewport or device preset, use retina scale, wait for a selector, delay, or network idle, and return PNG, JPEG, WebP, or PDF output. You can also supply custom CSS or JavaScript, headers, cookies, user-agent, timezone, geolocation, blocking rules, caching, signed links, asynchronous webhooks, and bulk requests.

Before capture, ScreenshotNeo accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

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

Use the API examples below with an access key; the parameter names used by many other screenshot APIs are accepted, which can simplify a migration. Full parameter details are in the ScreenshotNeo documentation.

cURL

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

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://playwright.dev"},
    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://playwright.dev',
});
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()));

Plans and cost control

Plan Allowance and price
Free 1,000 shots per month; no card
Starter $5 for 3,000 shots
Growth $15 for 15,000 shots
Pro $39 for 60,000 shots
Scale $99 for 250,000 shots
Business $249 for 1,000,000 shots

Yearly billing gives two months free, and every feature is available on every plan. Start with 1,000 free screenshots a month with no card; paid plans start at $5 for 3,000 shots.

FAQ

Can I change a viewport more than once in one test?

Yes. Call page.setViewportSize() again for the same page, then wait for any application-specific responsive transition before taking measurements or screenshots.

Does viewport width include the browser’s outer window or scrollbars?

Playwright’s values describe the emulated page viewport in CSS pixels, not the operating-system window frame. Validate the value your page receives with window.innerWidth when an application has unusual scrollbar behavior.

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

Should visual regression tests use one viewport or several?

Use the smallest matrix that covers your supported breakpoints. A single size is faster, while a few named phone, tablet, and desktop sizes catch layout changes that occur between breakpoints.

Frequently Asked Questions

Can I change a viewport more than once in one test?

Yes. Call page.setViewportSize() again for the same page, then wait for any application-specific responsive transition before taking measurements or screenshots.

Does viewport width include the browser’s outer window or scrollbars?

Playwright’s values describe the emulated page viewport in CSS pixels, not the operating-system window frame. Validate the value your page receives with window.innerWidth when an application has unusual scrollbar behavior.

Should visual regression tests use one viewport or several?

Use the smallest matrix that covers your supported breakpoints. A single size is faster, while a few named phone, tablet, and desktop sizes catch layout changes that occur between breakpoints.

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

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.