Find Elements Causing Horizontal Overflow
A console snippet that finds every element wider than the viewport, so you can track down mystery horizontal scrollbars.
The Problem
The page has a horizontal scrollbar and you don’t know which element is causing it. Instead of guessing and toggling overflow: hidden on suspects, find the actual offenders.
The Script
Paste into the console:
(() => {
const docWidth = document.documentElement.clientWidth;
const offenders = [];
document.querySelectorAll('*').forEach(el => {
const rect = el.getBoundingClientRect();
// Skip invisible / zero-area elements — they can't visibly cause scroll
if (rect.width < 1 && rect.height < 1) return;
// Skip fixed-position elements — they don't affect document scrollWidth
const position = getComputedStyle(el).position;
if (position === 'fixed') return;
const overflowRight = rect.right - docWidth;
const overflowLeft = -rect.left;
if (overflowRight > 1 || overflowLeft > 1) {
offenders.push({
el,
overflowRight: Math.round(overflowRight),
overflowLeft: Math.round(overflowLeft),
width: Math.round(rect.width),
position,
selector: getSelector(el)
});
}
});
function getSelector(el) {
if (el.id) return `#${el.id}`;
let path = el.tagName.toLowerCase();
if (el.className && typeof el.className === 'string') {
path += '.' + el.className.trim().split(/\s+/).join('.');
}
return path;
}
offenders.sort((a, b) =>
Math.max(b.overflowRight, b.overflowLeft) - Math.max(a.overflowRight, a.overflowLeft)
);
console.log(`document.documentElement.scrollWidth: ${document.documentElement.scrollWidth}, clientWidth: ${docWidth}`);
if (offenders.length === 0) {
console.log('No layout-affecting elements found overflowing the viewport width.');
} else {
console.log(`Found ${offenders.length} overflowing element(s):`);
console.table(offenders.map(o => ({
selector: o.selector,
position: o.position,
overflowRight_px: o.overflowRight,
overflowLeft_px: o.overflowLeft,
width_px: o.width
})));
window.$offenders = offenders.map(o => o.el);
console.log('Top offender stored in window.$offenders[0]:', offenders[0].el);
}
})();
How It Works
- Walks every element on the page and checks its
getBoundingClientRect()againstdocument.documentElement.clientWidth. - Skips
position: fixedelements since they don’t contribute todocument.scrollWidth. - Sorts offenders by how far they overflow, worst first.
- Stashes the matched elements on
window.$offendersso you can inspect or highlight the top one directly from the console ($offenders[0].style.outline = '2px solid red').