scrollWidth Detects Content Overflow
Compare scrollWidth with clientWidth to detect hidden content overflow, and read the offsetWidth gap that a scrollbar leaves behind.
Code
// offsetWidth/clientWidth/scrollWidth answer different questions:
// the border-box size, the visible box inside the borders, and the
// full content size the element can scroll through
const list = document.querySelector('#feed');
const report = {
offsetWidth: list.offsetWidth,
clientWidth: list.clientWidth,
scrollWidth: list.scrollWidth,
};
// Horizontal overflow exists exactly when the content is wider than
// the visible box — the check behind "is my layout broken" heuristics
const overflows = report.scrollWidth > report.clientWidth;
console.log(`overflow: ${overflows}`);
// A visible scrollbar shows up as the offsetWidth minus clientWidth gap
console.log(`scrollbar gap: ${report.offsetWidth - report.clientWidth}`);Three widths, three different questions
The file reads one element into report three ways: offsetWidth is the border-box size, clientWidth is the visible box inside the borders, and scrollWidth is the full content width the element can scroll through. The comparison report.scrollWidth > report.clientWidth is the entire overflow test — content wider than the visible box means clipped material exists.
What the console reports
Two lines are logged: `overflow: ${overflows}` — the boolean result of that comparison — and `scrollbar gap: ${report.offsetWidth - report.clientWidth}`, where a visible scrollbar appears as the offsetWidth-minus-clientWidth difference. The exact numbers depend on the page’s layout, so the snippet is a measurement, not a constant.
The line that answers “is my layout broken”
const overflows = report.scrollWidth > report.clientWidth;
That single comparison is the check behind the heuristic its own comment names: when it is true, something inside #feed is wider than the box showing it.
Interactive Tools for This Topic
FAQ
- Does scrollWidth Detects Content Overflow run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.