GenClass is open source.Star on GitHub

Horizontal scroll on mobile: find the element that sticks out.

A page scrolls sideways on a phone when one element is wider than the screen, usually an image, a table, a long URL, a 100vw box or a flex item that will not shrink. Find it with the console snippet below and fix that element, most often with a max-width of 100% or, for a flex or grid child, a min-width of 0. Hiding the overflow on body is a last resort.

Why a page scrolls sideways on a phone

A page scrolls sideways when its content is wider than the viewport: document.documentElement.scrollWidth is larger than its clientWidth. One element is enough: a 420 px image on a 390 px screen makes the whole page at least 420 px wide. Desktop windows are wide enough to hide most of these, so the bug shows up on phones first, whatever the framework.

Find the element wider than the screen

Open Chrome DevTools, turn on the device toolbar and type 360 in the width box (Chrome docs). Reload the page, then paste this into the Console:

(() => {
  const vw = document.documentElement.clientWidth; // viewport width without the scrollbar
  // true if el scrolls with the page: not position: fixed, and no box above it clips or scrolls
  const free = (el, own) => {
    for (let p = el; p && p !== document.body; p = p.parentElement) {
      const s = getComputedStyle(p);
      if (s.position === "fixed") return false;
      if ((own || p !== el) && s.overflowX !== "visible") return false;
    }
    return true;
  };
  const past = (r) => r.width > 0 && r.right + window.scrollX > vw + 1;
  const found = new Set();
  for (const el of document.body.querySelectorAll("*"))
    if (past(el.getBoundingClientRect()) && free(el, false)) found.add(el);
  const range = document.createRange(); // text that sticks out: long words and URLs
  const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
  for (let t = walk.nextNode(); t; t = walk.nextNode()) {
    range.selectNodeContents(t);
    if (t.data.trim() && past(range.getBoundingClientRect()) && free(t.parentElement, true)) found.add(t.parentElement);
  }
  const outer = [...found].filter((el) => ![...found].some((o) => o !== el && o.contains(el)));
  outer.forEach((el) => (el.style.outline = "3px solid red"));
  console.log(`page ${document.documentElement.scrollWidth} px wide, viewport ${vw} px`, outer);
})();

It compares the right edge of every element and every run of text with document.documentElement.clientWidth, the viewport width without the scrollbar (MDN); window.innerWidth would include the scrollbar (MDN). getBoundingClientRect() is relative to the viewport, so it adds window.scrollX (MDN). Fixed boxes and anything inside a box that clips or scrolls, such as a carousel, are skipped, because they do not widen the page. Text gets its own pass, since a long URL can stick out of a paragraph whose box fits.

The outermost offenders get a red outline. Fix one, reload and run it again, since a wide element can push its neighbors out too.

Common causes and the CSS that fixes each

  • An image or video with a fixed size: max-width: 100%; height: auto.
  • An iframe or embed with width="600": max-width: 100% plus box-sizing: border-box, since the default 2 px iframe border (HTML standard) otherwise sticks out by 4 px.
  • A wide table or code block: wrap the table in a div with overflow-x: auto, and give pre the same rule.
  • A long word, URL or email address: overflow-wrap: anywhere on the element that holds the text.
  • A fixed width such as width: 500px: add max-width: 100%, or write width: min(500px, 100%).
  • width: 100vw, which Tailwind's w-screen sets: use width: 100%, Tailwind's w-full (Tailwind docs).
  • A negative margin, such as a Bootstrap .row with no .container around it: Bootstrap's docs say to add .mx-0 to an edge-to-edge row (Bootstrap docs).
  • An off-canvas menu, or an element that slides in from the side, moved off screen with transform. Unless it is position: fixed, it still counts toward the page's overflow (CSS Transforms), so put overflow-x: clip on the section that holds it.
  • A flex or grid child that will not shrink: min-width: 0 on the child, or minmax(0, 1fr) for grid columns.

By default, viewport units are sized as if there were no scrollbar (CSS Values 4), but classic scrollbars take space (MDN), so a 100vw box sticks out by the scrollbar's width once the page is tall enough to scroll. Overlay scrollbars take no space, so on machines that use them a 100vw box sticks out only when it does not start at the left edge, for example inside a padded container.

Flex and grid items start at min-width: auto, which for an item without a set width means the min-content width of what it holds (MDN, Flexbox spec), so one long URL or wide pre sets the card's minimum and the row grows past the screen. min-width: 0 lets the card shrink. overflow-wrap: anywhere then wraps the text, and unlike break-word it also lowers the min-content width (MDN).

No viewport meta tag: the phone shows the desktop layout

If the whole page looks shrunk rather than shifted, check the <head>. Without a viewport meta tag, a phone lays the page out in a virtual viewport wider than the screen, such as 980 px, and shrinks it to fit (MDN). Text looks tiny, and small-screen media queries never match.

<meta name="viewport" content="width=device-width, initial-scale=1">

The same MDN page calls initial-scale=1 usually unnecessary, but says that without it the browser may zoom out when content overflows, so a page with one wide element can open zoomed out instead of scrolling sideways.

overflow-x: hidden vs clip, and why hiding is a last resort

The usual quick fix is overflow-x: hidden on body. It leaves the element too wide, and where you put it matters:

  • On body alone, the value moves to the viewport (CSS Overflow 3). In the test below, a touch pan still moved the page sideways.
  • On html and body together, or on a page wrapper, it stops the pan. But hidden makes body or the wrapper a scroll container (CSS Overflow 3), and a position: sticky header sticks to its nearest ancestor with a scrolling mechanism, even when that ancestor is not the one that scrolls (MDN), so the header scrolls away.

overflow-x: clip cuts off overflow without making a scroll container (CSS Overflow 3), so sticky keeps working. We checked each option in Chromium 159 with phone emulation at 390 px, the viewport tag above, a 600 px box and a sticky header:

What each overflow rule did in Chromium phone emulation
CSSA touch pan moves the page sidewaysSticky header after scrolling down
NoneYesSticks
body { overflow-x: hidden }YesSticks
html, body { overflow-x: hidden }NoScrolls away
A page wrapper with overflow-x: hiddenNoScrolls away
html, body { overflow-x: clip }NoSticks
A page wrapper with overflow-x: clipNoSticks

Every row that stops the pan also hides content. Fix the element first, and keep clip for the section that holds parts meant to sit off screen.

Test at 360 to 390 px wide

Check at 390, 360 and 320 px. In the device toolbar, pick a phone or set the device type to Mobile (Chrome docs). On a computer, Chrome applies the viewport tag only while it emulates a mobile device (DevTools Protocol), so with a desktop type a missing tag goes unnoticed. Chrome calls device mode "a first-order approximation" of a phone, so check on a real phone too.

To keep it fixed, add a Playwright test. Set isMobile so Playwright honors the viewport meta tag as a phone does (Playwright docs). This test fails on a missing tag and on a page wider than 360 px:

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

test.use({ viewport: { width: 360, height: 800 }, isMobile: true });

test("home page fits a 360 px phone", async ({ page }) => {
  await page.goto("/");
  await expect(page.locator('meta[name="viewport"]')).toHaveAttribute("content", /width=device-width/);
  const { scroll, client } = await page.evaluate(() => ({
    scroll: document.documentElement.scrollWidth,
    client: document.documentElement.clientWidth,
  }));
  expect(scroll, "the page is wider than the screen").toBeLessThanOrEqual(client + 1);
});

Where GenClass fits

GenClass Runtime (@genclass/runtime) has two measured visual checks for this, each with a fixed threshold. page-overflow-x reports a page whose scrollWidth is more than 1 px past its clientWidth at two readings 1 s apart. It names up to three of the outermost elements past the edge, the cause it found, such as a 100vw width or a flex item that cannot shrink, and a suggested CSS rule. viewport-meta-missing reports a phone (a touch screen 500 px wide or less) where no viewport tag sets width=device-width and the page is laid out at least 1.5 times as wide as the screen. By default both run only on development hosts such as localhost, where they print to the console.

Neither changes the page. Both measure the tab at its current width, so a desktop window shows only desktop overflow; page-overflow-x checks again 1 s after a resize. It skips overflow inside boxes that scroll or clip, and it stays quiet when html or body hides the overflow, including the body-only case in the table above. On faults the checks' author planted in GenClass's own demo, template and compatibility apps, in Chromium, page-overflow-x found 22 of 22 and viewport-meta-missing 11 of 11, with 0 false reports in 128 page views of those apps without faults. The false-report rate on other sites is not known (visual checks).

To check a public page without installing anything, run the free page check: it loads the page as a 390 px phone, narrows it to 360 and 320 px, widens it to 768 px, and flags a missing viewport tag.

Questions

Why does my website scroll sideways only on mobile?

One element is wider than the phone's screen, often an image, a table, a long URL or a fixed-width box. Run the console snippet at 360 px wide to find it.

Should I use overflow-x: hidden or overflow-x: clip?

Fix the wide element first. If something must stay cut off, use overflow-x: clip on the section that holds it, because hidden on html and body, or on a page wrapper, stops a sticky header from sticking.

Why does width: 100vw cause a horizontal scrollbar?

By default, viewport units are sized as if there were no scrollbar, so when a classic scrollbar takes up space, a 100vw box is wider than the page by the scrollbar's width. Use width: 100% instead.

Why does my site look zoomed out on a phone?

Usually the viewport meta tag is missing, so the phone lays the page out wider than the screen and shrinks it. Add the tag with width=device-width and initial-scale=1, then fix any element that is still too wide.

How can I check a page for horizontal scroll?

Load it at 360 px wide with a mobile device type in Chrome DevTools and run the snippet above. For a public page, GenClass's free page check loads it at 390, 360 and 320 px and reports sideways scrolling.

Related: a page frozen after a modal closes and front-end bugs that raise no error.

Talk to sales

Tell us about your team and what you need. A person writes back, usually within a day.