logo of Screenshot for Web
Free toolsPlaygroundDocsBlogPricing
LoginDashboard

Company

HomeFeaturesPricingBlogFacts

Screenshot Tools

Website ScreenshotsFull Page ScreenshotsScrolling ScreenshotsWebsite HistoryPDF Generation APIScreenshot API

Legal

Terms of UsePrivacy PolicyCookie PolicyCopyrightSecurity

Support

FAQSupportContact UsAPI Status
screen shot for web logo

No clutter. No distractions. Just clean, full-page screenshots with smart customization.

© 2026 HYDRANODE LTD. All rights reserved.

Screenshot for Web is operated by HYDRANODE LTD, a company registered in England and Wales, company number 15672526. Registered office: 124 City Road, London, London, England, EC1V 2NX.

FacebookInstagramLinkedInYouTube
  1. Home
  2. Blog
  3. Guides

How to screenshot one element by CSS selector in Puppeteer and Playwright, tested

We captured single elements in Puppeteer and Playwright and found six ways it goes wrong, from fixed headers to cut-off shadows. Tested helpers for both included.

Screenshot for Web·October 26, 2026·8 min read

Sources

  1. Puppeteer API: ElementHandle.screenshot()
  2. Puppeteer API: ScreenshotOptions
  3. Puppeteer API: ElementScreenshotOptions
  4. Puppeteer guide: Page interactions (locators and the >>> combinator)
  5. Playwright API: locator.screenshot()
  6. Playwright: Auto-waiting and actionability checks
  7. Playwright: Locators (strictness and Shadow DOM)
  8. MDN: Element.getBoundingClientRect()
  9. MDN: box-shadow

How this article was made

Researched and drafted with AI assistance from the sources listed, and from reading Puppeteer's own ElementHandle.screenshot source in the installed package. All code was run by us on 26 October 2026 on an Apple Silicon Mac with Puppeteer 25.16.0 (Chrome for Testing 156.0.8078.47) and Playwright 1.64.1 (Chromium 156.0.8078.4). The test page was written for this article and served locally; the real-page checks used news.ycombinator.com, python.org and MDN's box-shadow page. Every number, image and error message in the article comes from those runs.

Capture any page without ads, banners or chat widgets, free and without an account.

Try the free tools

More articles

  • News

    Puppeteer 25.19 stops print and dark mode emulation from cancelling each other

    Before Puppeteer 25.19.0, emulateMediaType and emulateMediaFeatures reset each other, losing print or dark mode. Our tests, the fix and a workaround.

    November 26, 2026
  • News

    Chrome 158 drops XSLT: what it does to screenshots of sitemaps and feeds

    We captured eight live sitemaps in Chrome 156 and Chromium 158. Styled pages turn into raw XML, a red warning bar is already in captures, and two fixes work.

    November 9, 2026
  • Research

    Chrome DevTools' full-size screenshot: where it fails on long and lazy pages

    We ran DevTools' full-size screenshot on six long pages: it stops at 16,384 pixels and misses content that appears on scroll. Here's why, and the fixes that worked.

    November 8, 2026

To screenshot one element, find it with a CSS selector and call screenshot() on it: elementHandle.screenshot() in Puppeteer, locator.screenshot() in Playwright. Both crop a normal page capture to the element's box. That is two lines of code, and it works for simple cases.

We wanted to know where it breaks. So we built a test page with the awkward cases real sites have, captured each one in Puppeteer 25.16.0 and Playwright 1.64.1 on 26 October 2026, and checked every image. We found six problems: selectors that match several elements, elements that aren't there yet or are hidden, shadow DOM, fixed headers painted into the middle of the image, box shadows cut off, and elements captured mid-animation. Below are the results, then one tested helper per library that handles all six.

The basic call

Puppeteer: wait for the element, then screenshot the handle.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
  await page.goto('http://127.0.0.1:8123/');

  const card = await page.waitForSelector('#pro', { visible: true });
  await card.screenshot({ path: 'pro.png' });
  console.log('saved pro.png');

  await browser.close();
})();

Playwright: the locator waits for you.

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
  await page.goto('http://127.0.0.1:8123/');

  await page.locator('#pro').screenshot({ path: 'pro.png' });
  console.log('saved pro.png');

  await browser.close();
})();

Both printed saved pro.png. The card is 260 by 172.08 CSS pixels. At a device pixel ratio of 2, Puppeteer's image was 520×344 and Playwright's 520×346: Puppeteer dropped the fraction of a pixel and Playwright rounded the box out to 173 pixels. Keep that in mind if you compare images from the two libraries pixel by pixel.

How it works underneath: Puppeteer's documentation says the method "scrolls element into view if needed, and then uses Page.screenshot()". Its source shows the rest. It reads the element's bounding box, adds the scroll position, and passes that rectangle as clip to an ordinary page screenshot. Playwright's documentation describes the same idea: a screenshot of the page, clipped to the element's size and position, after its actionability checks. That one fact explains most of what follows. The image is a crop of the page at that moment, so anything painted over the element is in it, and anything outside the element's border box is not.

What each library did with the awkward cases

Same page, same 1280×800 viewport, Chrome 156 in both.

CasePuppeteer 25.16.0Playwright 1.64.1
.card matches 3 elementspage.$() took the first one silentlyThrew strict mode violation: locator('.card') resolved to 3 elements
Element added 1.5 s after loadpage.$() returned null, then TypeErrorWaited and captured it (1,869 ms after goto)
display: noneError: Node is either not visible or not an HTMLElementWaited, then TimeoutError after 30 s
visibility: hiddenSaved a blank 900×24 imageWaited, then TimeoutError
Element inside an open shadow rootPlain .badge returned null; price-widget >>> .badge workedPlain .badge worked
Table taller than the viewport (1,846 px)Captured in full, fixed header painted insideCaptured in full, fixed header painted inside
Scrollable boxOnly the visible part of its contentOnly the visible part of its content

Two of these deserve a closer look.

Hidden elements. Playwright only screenshots an element that passes two checks, which its documentation calls Visible (a non-empty bounding box and no visibility:hidden) and Stable (the same bounding box for two animation frames in a row). A hidden element never passes, so the call waits for the default action timeout. With no timeout set, ours waited 30,008 ms before throwing. Puppeteer has no such check for visibility: hidden, because the element still has a box: it saved a 900×24 image of empty page. If you capture many selectors in a batch, set a short timeout in Playwright, and use waitForSelector(selector, { visible: true }) in Puppeteer.

Shadow DOM. Playwright's locators pierce open shadow roots by default. Puppeteer's page.$() does not, but its query syntax has a deep combinator, >>>, that "selects matching elements under the parent element at any depth". This matters on real sites. On MDN's box-shadow page, the browser compatibility table is not in the page at the load event, and once it renders it sits two shadow roots deep, inside mdn-compat-table-lazy and then mdn-compat-table. page.$('table.bc-table') returned null both at load and after the table appeared. page.locator('>>> table.bc-table') found it and captured it in 825 ms. In Playwright, a plain locator('table.bc-table') counted 0 matches at load and still captured the table, because the screenshot call waited for it.

On Hacker News, tr.athing matched 30 rows. Puppeteer would capture the first without a word; Playwright refuses until you say which one, for example with .first() or a tighter selector. We prefer Playwright's behaviour here: a selector that matches 30 things is usually a bug.

Problem: fixed headers land in the middle of the image

The hero image above shows the most surprising result. The table is taller than the viewport, so the screenshot has to reach beyond it. Puppeteer scrolled until the table's bottom was in view: after the call, the window was scrolled to 2,064 pixels and the table's top was 523 pixels above the viewport. The fixed header sits at the top of the viewport, so it was painted 523 pixels into the table, right across row 12. Playwright's image had the header in exactly the same place, from pixel row 523 to 578.

A sticky header or a cookie bar fixed to the bottom of the screen does the same. Any element whose box overlaps a fixed bar on screen is affected, not just tall ones.

The fix is to hide fixed and sticky elements before the capture, but not the element you want or anything inside it. Playwright's style option is a stylesheet applied only while the screenshot is taken, and style: 'header { visibility: hidden !important; }' removed the header from our table capture. On real sites you rarely know the header's selector, so the helpers below find fixed and sticky elements by their computed position instead.

Problem: shadows and rounded corners are cut off

Two captures of the Pro pricing card. On the left, the bounding box only: the card's drop shadow is missing and the grey page background shows in its rounded corners. On the right, clipped with 40 pixels of padding: the full shadow is visible, along with the edges of the neighbouring cards.

The clip is the element's bounding box, which MDN defines as the smallest rectangle containing the element "including its padding and border-width". A box-shadow is outside it: MDN's box-shadow page says a shadow "does not impact" box model dimensions. So the shadow is gone, and the page background shows in the rounded corners.

Two fixes, depending on what you want:

  1. Keep the shadow. Capture a larger rectangle. Puppeteer's ElementHandle.screenshot() treats clip as relative to the element, and a negative x and y work, so clip: { x: -40, y: -40, width: box.width + 80, height: box.height + 80 } gives 40 pixels of margin. Our card's shadow is 0 12px 28px, and 40 pixels (offset plus blur) held all of it. Playwright's element screenshot has no clip, so the helper below uses a full-page screenshot clipped to the padded box instead. Padding also brings in whatever is next to the element: in the image above, the edges of the neighbouring cards.
  2. Keep only the element, with transparent corners. Make the page background transparent and pass omitBackground: true. Puppeteer's documentation says this "hides default white background and allows capturing screenshots with transparency". Playwright's reference adds that it doesn't apply to JPEG. It also only helps if the page and the element's containers don't paint a background of their own, which is why we set the page's background to transparent first. We did that with page.addStyleTag({ content: 'html, body { background: transparent !important; }' }) on a fresh page, then captured a card both ways. Without omitBackground, its corner pixel was opaque near-white (Chrome's default background). With it, the same pixel had an alpha of 7 out of 255: transparent apart from a trace of the card's own shadow.

Problem: animated elements move between measuring and capturing

Two captures of a green notification that slides in from the right. Captured mid-animation, the text is cut off on the left ('ved. Your capture is ready.') and grey background fills the right side. With animations turned off first, the whole notification is visible.

Our notification slides in over 1.2 seconds. Puppeteer measured it straight after goto, at x = 440, then took the picture. By then the notification had moved further left, so the image cut off the start of the text and showed page background on the right.

Playwright's Stable check caught this. With default options, the call waited until the element stopped moving and took 1,488 ms. With animations: 'disabled' it took 87 ms. That option fast-forwards finite CSS animations and transitions to their end and resets infinite ones, according to the API reference. In Puppeteer, inject a stylesheet that turns animations and transitions off before measuring.

A tested helper for Puppeteer

This waits for a visible element (selectors with >>> work), turns off animations, hides fixed and sticky elements that aren't the target or inside it, and keeps optional padding.

const puppeteer = require('puppeteer');

// Screenshot one element: wait for it, freeze animations, hide fixed and
// sticky bars that would paint over it, and keep `padding` px around it.
async function screenshotElement(page, selector, { path, padding = 0, timeout = 15000 } = {}) {
  const el = await page.locator(selector).setTimeout(timeout).waitHandle();
  await page.addStyleTag({ content:
    '*, *::before, *::after { animation: none !important; transition: none !important; }' });
  await el.evaluate((target) => {
    for (const node of document.querySelectorAll('body *')) {
      const { position } = getComputedStyle(node);
      if ((position === 'fixed' || position === 'sticky') && !node.contains(target) && !target.contains(node)) {
        node.style.setProperty('visibility', 'hidden', 'important');
      }
    }
  });
  const box = await el.boundingBox();
  return el.screenshot({
    path,
    clip: { x: -padding, y: -padding, width: box.width + padding * 2, height: box.height + padding * 2 },
  });
}

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
  await page.goto('http://127.0.0.1:8123/');
  for (const [selector, file, padding] of [
    ['#toast', 'out/helper-pptr-toast.png', 0],
    ['#late-card', 'out/helper-pptr-late.png', 24],
    ['#pro', 'out/helper-pptr-pro.png', 40],
    ['price-widget >>> .badge', 'out/helper-pptr-badge.png', 0],
    ['#pricing-table', 'out/helper-pptr-table.png', 0],
  ]) {
    const t0 = Date.now();
    const png = await screenshotElement(page, selector, { path: file, padding });
    console.log(selector, `${png.readUInt32BE(16)}x${png.readUInt32BE(20)}`, `${Date.now() - t0} ms`);
  }
  await page.goto('https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow');
  const png = await screenshotElement(page, '>>> table.bc-table', { path: 'out/helper-pptr-mdn.png', padding: 8 });
  console.log('MDN >>> table.bc-table', `${png.readUInt32BE(16)}x${png.readUInt32BE(20)}`);
  await browser.close();
})();

Output (sizes are at a device pixel ratio of 2):

#toast 624x112 90 ms
#late-card 616x328 1467 ms
#pro 680x504 50 ms
price-widget >>> .badge 328x82 63 ms
#pricing-table 1800x3692 119 ms
MDN >>> table.bc-table 1440x1030

The notification came out whole, the late card was waited for, the table had no header across it, and the shadow-DOM badge and MDN's nested table were found. The helper changes the page: hidden headers stay hidden and animations stay off. Run it last, or reload the page before doing anything else with it.

A tested helper for Playwright

Playwright already waits, checks stability and can turn animations off, so the helper only hides fixed elements and adds padding.

const { chromium } = require('playwright');

// Screenshot one element: Playwright waits for it and freezes animations;
// we hide fixed and sticky bars and keep `padding` px around it.
async function screenshotElement(page, selector, { path, padding = 0, timeout = 15000 } = {}) {
  const el = page.locator(selector);
  await el.waitFor({ state: 'visible', timeout });
  await el.evaluate((target) => {
    for (const node of document.querySelectorAll('body *')) {
      const { position } = getComputedStyle(node);
      if ((position === 'fixed' || position === 'sticky') && !node.contains(target) && !target.contains(node)) {
        node.style.setProperty('visibility', 'hidden', 'important');
      }
    }
  });
  if (!padding) return el.screenshot({ path, animations: 'disabled', timeout });
  await el.scrollIntoViewIfNeeded();
  const box = await el.boundingBox();
  const [scrollX, scrollY] = await page.evaluate(() => [window.scrollX, window.scrollY]);
  return page.screenshot({
    path, fullPage: true, animations: 'disabled',
    clip: { x: box.x + scrollX - padding, y: box.y + scrollY - padding,
            width: box.width + padding * 2, height: box.height + padding * 2 },
  });
}

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
  await page.goto('http://127.0.0.1:8123/');
  for (const [selector, file, padding] of [
    ['#toast', 'out/helper-pw-toast.png', 0],
    ['#late-card', 'out/helper-pw-late.png', 40],
    ['#pro', 'out/helper-pw-pro.png', 40],
    ['.badge', 'out/helper-pw-badge.png', 0],
    ['#pricing-table', 'out/helper-pw-table.png', 0],
    ['#pricing-table', 'out/helper-pw-table-padded.png', 16],
  ]) {
    const t0 = Date.now();
    const png = await screenshotElement(page, selector, { path: file, padding });
    console.log(selector, `padding ${padding}`, `${png.readUInt32BE(16)}x${png.readUInt32BE(20)}`, `${Date.now() - t0} ms`);
  }
  await page.goto('https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow');
  const png = await screenshotElement(page, 'table.bc-table', { path: 'out/helper-pw-mdn.png', padding: 8 });
  console.log('MDN table.bc-table', `${png.readUInt32BE(16)}x${png.readUInt32BE(20)}`);
  await browser.close();
})();

Output:

#toast padding 0 624x114 86 ms
#late-card padding 40 680x392 1854 ms
#pro padding 40 680x504 66 ms
.badge padding 0 330x84 62 ms
#pricing-table padding 0 1800x3694 126 ms
#pricing-table padding 16 1864x3756 111 ms
MDN table.bc-table 1440x1029

The padded path uses the page's own coordinates: boundingBox() is relative to the viewport, as with getBoundingClientRect(), so the helper adds the scroll offsets, which is the conversion MDN gives. We checked the padded table's first and last rows were both in the image and the header was gone. A selector that matches several elements still throws here; that is deliberate.

Checklist

  1. Make the selector match exactly one element. Playwright enforces it; Puppeteer quietly takes the first.
  2. Wait for the element to be visible, with a timeout you choose.
  3. Use >>> in Puppeteer for elements in shadow DOM. Playwright needs nothing.
  4. Hide fixed and sticky elements, or they can appear inside the image.
  5. Turn animations off before measuring.
  6. Add padding if the element has a shadow, or use omitBackground for transparent corners.
  7. Set a device pixel ratio of 2 if the image will be shown on high-density screens.
  8. Remember a scrollable box is captured as it is scrolled: only its visible part appears.