Which element is causing the horizontal scrollbar?

2019-04-21 23:16发布

问题:

Horizontal scrollbars on web sites and HTML apps are generally bad for usability and unwanted. It's reasonably common to find them cropping up unexpectedly and I'm in need of a way to quickly debug and remove them.

What is the quickest and easiest way to find offending HTML elements in your design?
And is there a script or tool to automate this?

Yes, you can go through your page deleting/hiding elements one by one until you find a suspect, but this is time consuming, especially if there are multiple offending elements. It would be great to click a shortcut or run a script and have all the suspected elements highlighted, outlined or printed to the console.

To clarify: the problem is not how to solve it, but how to detect it. I'd like a general solution which can work whenever this issue appears.

回答1:

In a narrower scope, you can use jQuery (to get the width) and node.scrollWidth to get nodes that have content that overflow their bounds.

http://jsfiddle.net/tomprogramming/v3Q6W/3/



回答2:

If you let your content flow, you won't get horizontal scroll bars in the first place. Don't put too many width constraints. Usually, you only set the (minimum) width of the main column containing all your content. You might also constrain the width of some vertical bars (e.g. navigation bars). Otherwise, use CSS width property (and other such mechanisms) sparingly.

The CSS white-space property also tends to necessitate scrollbars; use this property judiciously. This is really only for formatting code, where it is important to maintain line breaks as they appear in HTML source for alignment purposes.