Skip to content
drugoi.dev
TwitterTelegramLinkedIn1on1

How to Find an Element That Overflows the Viewport

JavaScript, CSS, Markup, debugging, frontend

The post was originally written for the Telegram channel.

Previously, when I often worked on layout and made adaptive interfaces, sometimes I was faced with the fact that some elements went beyond the viewport and horizontal scroll zones appeared.

It's not always entirely obvious which element caused this behavior; sometimes it may not even be physically visible on the page.

For such cases, I used the following hack, via custom CSS:

*,
*:after,
*:before {
outline: 1px solid red;
}

We attach a 1px red outline to all elements on the page and find the culprits for the bad layout.

Today I saw a more elegant solution using JavaScript:

document.querySelectorAll('*').forEach((el) => {
if (el.offsetWidth > document.documentElement.offsetWidth) {
console.log(el);
}
});

We look for all elements on the page, if the offsetWidth of the element is greater than the offsetWidth of our document, we display the element in the console, and after that we can (at least in Chrome) right-click on the element in the console and select Scroll into view to see it on the page.

All that remains is to fix the problem and continue with the layout.

💚 Nikita Bayev Paper Company
Theme by LekoArts