Element overflow fixing

Hi! today we’ll discuss one of the cutest solutions for html element overflow problem.

Mistakes in sizing and positioning of containers and elements on a web page results in usually unneeded horizontal scroll bar. And if your markup is complex enough it’s usually takes a lot of time to find elements which caused overflow. Sure you can stay blind to this by adding overflow:hidden; but! you shouldn’t do this anyway. Let’s dive into one cute solution for this…

Some time ago I’ve met this problem and found myself seeking problematic element  in Chrome Dev tools for an hour with no luck. I’ve googled a bit and found cute solution by Chris Coyier on https://css-tricks.com/findingfixing-unintended-body-overflow/

The idea is brilliant – we are programmers! so don’t waste time looking for overflown element by yourself – give this job to your browser and then work only on fix.

Thanks to Chris for pointing me in a right direction! So I used his script and it worked fine, except it cant handle absolute positioned elements.

I’ve extended it a bit and now it works perfectly with absolute positioned elements as well.

The idea is to use Bounding Client Rect of element along side with offsetWidth  of element. Because offsetWidth contains total width of element but  Bounding Client Rect in right property contains absolute position of the righter most point of element. So it’s perfect to check weather absolute positioned element is the cause of overflow.

Here’s a result. Just save it as .js file and link to your page. And as you’ll reload your page in a developer console there will be all your elements which caused overflow.

If some scripting is cause of your overflown elements call this function manually from the developers console findOverflow(); as you’ll encounter horizontal scrollbar at some point.

Snippet:


// originaly based on code from https://css-tricks.com/findingfixing-unintended-body-overflow/
// improved to handle absolute positioned elements shifted to right making overflow happend.
function findOverflow(){
var docWidth = document.documentElement.offsetWidth;
[].forEach.call(
document.querySelectorAll('*'),
function(el) {
var rect= el.getBoundingClientRect();
if (el.offsetWidth > docWidth ||rect.right>docWidth) {
console.log(el);
}
}
);
}
findOverflow(); // call it as script loads. Also you can call it later manually from a console.

Happy codding!

Respectfully yours, Mikhail Durnev.

 

Leave a Reply

Your email address will not be published. Required fields are marked *