Web Development

Detecting element causing CSS overflow

Advertisements

CSS overflows are an annoyance that keep showing up once in a while and are really hard to debug. Unwanted and unexpected scrollbars can lead to hours of inspecting the DOM to figure out what element is causing the issue and clicking random elements in the Chrome dev tools until you find the culprit.

A simple programmatic way of figuring out what is causing the issue can be:

document.querySelectorAll('*').forEach(elem => {
  if (elem.offsetWidth > document.documentElement.offsetWidth) {
      console.log('Problem child: ', elem);
  }
});
JavaScript

This will log all the elements that have an offset width greater than the document’s width. And then you get to decide what you want to do with all these elements that are wider than the viewport.

Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCR which is a developer community in Delhi, India.

View Comments

  • What would I do with this? Sorry, I'm an amateur. I think I'm having such an issue with my wordpress site and would like to see if it would help me. Thanks, Grant

    • This script identifies elements on a webpage that are wider than the viewport (the visible area of the web page). It logs these "problem child" elements to the console, which can help you debug layout issues where elements are causing horizontal scrolling.

Share
Published by
Saransh Kataria
Tags: CSS

Recent Posts

Remapping keyboard keys to avoid Carpal Tunnel

I am terrible at optimizing my keyboard layout for anything. But off lately, my little…

3 months ago

Fixing cookies are blocked for a website with shields down on Brave

I recently switched completely to the Brave browser and have set ad blocking to aggressive…

7 months ago

Generating a QR code using Node.js

I was preparing a slide deck for a hackathon and decided to put in a…

8 months ago

How to clear the global npx cache

I have been using npx a lot lately, especially whenever I want to use a…

9 months ago

Copy/Pasting output from the terminal

Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…

9 months ago

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

10 months ago
Advertisements