Fix Puppeteer Flexbox Alignment in Screenshots
Puppeteer screenshots often show flexbox layouts that look different from your browser — elements shifted, overflowing, or misaligned. This guide explains the common causes and gives you a step-by-step fix that makes screenshots match your intended design.
What You'll Need
- A Node.js project with Puppeteer installed
- Access to the HTML/CSS you're screenshotting (local file or URL)
- Basic familiarity with CSS flexbox and Puppeteer's page methods
Step-by-Step
- Set a consistent viewport size. Flexbox alignment depends heavily on available width and height. Before taking a screenshot, call
page.setViewport({ width: 1280, height: 720 })(or your desired dimensions) and ensure the same viewport is used in your browser's dev tools for comparison. - Wait for fonts and images to load. Fonts loading late can cause text reflow and shift flex items. Use
await page.evaluate(() => document.fonts.ready)andawait page.waitForNetworkIdle()before capturing. - Disable animations and transitions. CSS animations can leave elements mid-position. Inject a style to disable them:
await page.addStyleTag({ content: '* { animation: none !important; transition: none !important; }' }). - Check for scrollbar differences. A scrollbar appearing in Puppeteer but not in your browser (or vice versa) changes available width. Force consistent scrollbars by setting
overflow: scrollon the body in a test style, or usepage.setScrollBarStyleif available. - Ensure the page height is fully captured. If your screenshot is cut off, flex items may appear misaligned because the bottom part is missing. Use
page.screenshot({ fullPage: true })or set a fixed height that matches your content. - Match device scale factor. If your browser uses a different device pixel ratio, screenshots can look blurry or misaligned. Set
deviceScaleFactor: 1in viewport options for consistency. - Use a consistent user agent. Some sites serve different CSS based on user agent. Set
page.setUserAgent('Your-User-Agent')to match your testing browser. - Verify flex-basis and min-width. Flex items can shrink unexpectedly. In your CSS, ensure flex items have
min-width: 0or explicitflex-basisvalues to prevent them from overflowing or collapsing. - Take a test screenshot and compare. Capture a screenshot, open it side-by-side with your browser's rendering, and note the exact differences. Use that to adjust either your CSS or your Puppeteer settings.
Common Mistakes
- Forgetting to set viewport before navigation. If you set viewport after
page.goto(), the page may have already rendered with a different size. - Using
page.screenshot()without waiting for network idle. Images or web fonts may still be loading, causing layout shift. - Assuming your browser and Puppeteer use the same default viewport. Puppeteer's default is 800x600, which is much smaller than most desktop browsers.
- Ignoring scrollbar width. On Windows, scrollbars take up ~17px; on macOS, they overlay and take no space. This difference alone can break flex alignment.
- Not checking for CSS media queries. If your CSS uses
@media (min-width: 768px), a small viewport will apply different styles.
Tips
- Use a headless browser that matches your testing browser. If you use Chrome, launch Puppeteer with
executablePath: '/path/to/chrome'to ensure the same rendering engine version. - Set a fixed width on flex containers. For screenshots, temporarily add a style like
body { width: 1280px; }to avoid percentage-based width differences. - Use
page.emulateMediaType('screen'). If your CSS has print styles, they can affect layout when Puppeteer defaults toprintmedia type. - Take multiple screenshots at different viewport sizes to identify if the issue is responsive-related.
- Use Puppeteer's
page.evaluateto loggetBoundingClientRect()values for key flex items to compare with your browser's dev tools.
Troubleshooting
If the screenshot still doesn't match:
- Check for CSS custom properties (variables). If your CSS uses variables that are set via JavaScript, ensure they are set before the screenshot. Use
page.waitForFunction()to wait for a specific condition. - Verify that your page is not in a 'reduced motion' state. Some sites change layout when
prefers-reduced-motionis set. Usepage.emulateMediaFeatures([{ name: 'prefers-reduced-motion', value: 'no-preference' }]). - Try a different Puppeteer version. Occasionally, a bug in Puppeteer's rendering can cause layout issues. Update to the latest version or try a previous stable one.
- If using a remote URL, check for A/B tests or cookies. The page may serve different content based on cookies. Use
page.setCookie()to match your browser's session. - As a last resort, use a screenshot comparison tool like pixelmatch to identify exact pixel differences and adjust your CSS accordingly.
Frequently Asked Questions
Why does my flexbox look fine in Chrome but not in Puppeteer?
Because Puppeteer uses a headless browser that may have a different default viewport size, device scale factor, or scrollbar behavior. Also, fonts and images may load at different times.
How do I make Puppeteer use the same viewport as my browser?
Open your browser's dev tools, note the viewport dimensions (e.g., 1280x720), and set that exactly in page.setViewport(). Also match the device scale factor (usually 1).
Can I force flex items to not shrink in Puppeteer?
Yes, add CSS like flex-shrink: 0 to the flex items, or set min-width: 0 to allow shrinking but prevent overflow. You can inject this via page.addStyleTag() just for the screenshot.
Why is my full-page screenshot missing the bottom of the flex container?
Full-page screenshots capture the entire scrollable area, but if the flex container's height is set to 100vh, it may only cover the viewport. Use min-height: 100vh instead, or set a fixed height that accommodates the content.
Does Puppeteer support CSS flexbox correctly?
Yes, Puppeteer uses Chromium's rendering engine, which fully supports flexbox. Any differences are due to environment settings, not missing feature support.
How do I take a screenshot of a specific flex element only?
Use page.$('.flex-container') to get the element handle, then call elementHandle.screenshot(). This captures only that element's bounding box.