An element overflows when its content is larger than the box that holds it. You usually find out by accident: a title runs past its card, a table pushes the page sideways on a phone, or a "Read more" link shows up under text that was never cut off. Checking for overflow in JavaScript lets you act on it, for example by showing a tooltip only for truncated text or revealing a button only when a paragraph is clamped.
This guide covers the basic check, the edge cases that give wrong answers, a reusable helper, a watcher that reacts when overflow starts or stops, and three practical examples, including a snippet that finds the element causing a horizontal scrollbar.
How overflow is measured
The browser exposes two sizes for every element: the visible box and the full size of its content. Overflow is the difference between them.
| Property | Measures | Includes | Excludes |
|---|---|---|---|
clientWidth, clientHeight |
The visible box | Content and padding | Border, margin, scrollbar |
offsetWidth, offsetHeight |
The box with its frame | Content, padding, border, scrollbar | Margin |
scrollWidth, scrollHeight |
The full content, including the part that is cut off or scrolled out of view | Content and padding | Border, margin, scrollbar |
scrollWidth and clientWidth are measured the same way. They are equal when everything fits and differ when something does not.
The basic check
const horizontal = element.scrollWidth > element.clientWidth;
const vertical = element.scrollHeight > element.clientHeight;
if (horizontal || vertical) {
// The content is larger than its box
}
This works for elements with overflow: hidden, auto and scroll. In current browsers it also works with overflow: visible, because scrollWidth and scrollHeight report the content size whatever the overflow value is.
Use clientWidth rather than offsetWidth for the comparison. offsetWidth includes the border, so a 2px border can hide a 2px overflow.
Edge cases that give wrong answers
| Situation | What happens | What to do |
|---|---|---|
| Rounding | Both properties return whole numbers, so zoom levels and fractional widths can make scrollWidth exceed clientWidth by 1 when nothing is cut off. |
Allow a tolerance of 1px, as the helper below does. |
| Inline elements | A plain <span> has no box of its own, so clientWidth is 0 and the check never reports overflow. |
Set display: block or inline-block on the element you measure. |
| Hidden elements | With display: none every size is 0, so the answer is always "no overflow". |
Measure after the element becomes visible. |
| Overflow to the top or left | Content pushed in those directions, for example by negative margins or offsets, cannot be scrolled to and is not counted. | Use getBoundingClientRect() on the child when you need to catch it. |
| Measuring too early | Web fonts and images that load later change the content size after your first check. | Re-check when they finish. The watcher below does this. |
| Page-level check | window.innerWidth includes the vertical scrollbar, so comparing against it gives false results. |
Compare document.documentElement.scrollWidth with document.documentElement.clientWidth. |
scrollWidth or clientWidth forces the browser to calculate layout. That is fine for a handful of elements. In a loop that also changes styles, it can slow the page down, so do all the reads first and the writes after.
A reusable helper
The helper below returns which directions overflow and by how many pixels, with the tolerance built in.
// Compares the full content size with the visible box.
// tolerance absorbs the 1px rounding differences that zoom and fractional sizes create.
function getOverflow(element, tolerance = 1) {
const x = element.scrollWidth - element.clientWidth;
const y = element.scrollHeight - element.clientHeight;
return {
horizontal: x > tolerance,
vertical: y > tolerance,
overflowX: Math.max(0, x),
overflowY: Math.max(0, y),
};
}
function isOverflowing(element, tolerance = 1) {
const { horizontal, vertical } = getOverflow(element, tolerance);
return horizontal || vertical;
}
getOverflow() gives you the details. isOverflowing() is the short form for the common yes-or-no case. Pass 0 as the tolerance if you need to catch a single pixel.
React when overflow starts or stops
A one-time check goes stale. The window gets resized, text is edited, an image loads, a web font arrives. watchOverflow() calls your function once at the start and again only when the overflow state changes.
// Usage
const stop = watchOverflow(element, ({ horizontal, vertical }) => {
console.log({ horizontal, vertical });
});
// Later, when you no longer need it
stop();
// Calls callback(result) once on start and again only when the overflow state changes.
// Returns a function that stops watching.
function watchOverflow(element, callback, { tolerance = 1 } = {}) {
let last = "";
let frame = 0;
let stopped = false;
function check() {
frame = 0;
const result = getOverflow(element, tolerance);
const key = `${result.horizontal}:${result.vertical}`;
if (key === last) return;
last = key;
callback(result);
}
// Several triggers in one frame become a single check.
const schedule = () => {
if (!stopped && !frame) frame = requestAnimationFrame(check);
};
const resizeObserver = new ResizeObserver(schedule);
// A fixed-size box does not resize when its content grows,
// so the children are observed as well.
function observeBoxes() {
resizeObserver.disconnect();
resizeObserver.observe(element);
for (const child of element.children) resizeObserver.observe(child);
}
const mutationObserver = new MutationObserver(() => {
observeBoxes();
schedule();
});
mutationObserver.observe(element, { childList: true, characterData: true, subtree: true });
observeBoxes();
schedule();
if (document.fonts) document.fonts.ready.then(schedule); // web fonts change text width
return function stop() {
stopped = true;
resizeObserver.disconnect();
mutationObserver.disconnect();
cancelAnimationFrame(frame);
frame = 0;
};
}
Why it uses several observers
ResizeObserveron the element catches changes to its box, such as a window resize or a container that changes width.ResizeObserveron the children catches content growing inside a box of fixed size. The parent does not resize in that case, so observing only the parent would miss it.MutationObservercatches text and element changes, and re-observes the children whenever they change.document.fonts.readytriggers one more check after web fonts load, which changes text width.- All triggers feed into
requestAnimationFrame(), so several events in one frame produce a single check. This is a form of throttling, and debouncing and throttling in JavaScript explained covers the idea in general. - The returned
stop()function disconnects everything, including a check that was already queued.
Practical examples
Show a tooltip only for truncated text
Truncated text uses three CSS properties together. The element must be a block, or the measurement is 0.
.truncate {
display: block;
max-width: 240px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
document.querySelectorAll(".truncate").forEach((element) => {
watchOverflow(element, ({ horizontal }) => {
if (horizontal) element.title = element.textContent.trim();
else element.removeAttribute("title");
});
});
The full text is already in the page, so screen readers read all of it. The title tooltip helps mouse users only, so give touch users another way to see the text if it matters, such as a tap to expand.
Show "Read more" only when text is clamped
.clamp {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
<p class="clamp">A long paragraph goes here.</p>
<button type="button" hidden>Read more</button>
document.querySelectorAll(".clamp").forEach((text) => {
const button = text.nextElementSibling;
const stop = watchOverflow(text, ({ vertical }) => {
button.hidden = !vertical;
});
button.addEventListener("click", () => {
stop();
text.classList.remove("clamp");
button.hidden = true;
});
});
The button stays hidden for short text and appears only when the paragraph is actually cut off, even after the window is resized. Once the user expands the text, stop() ends the watching.
Find what causes a horizontal scrollbar
If the page scrolls sideways, first confirm it, then list the elements that stick out of the viewport.
const page = document.documentElement;
const hasHorizontalScroll = page.scrollWidth > page.clientWidth;
function findWideElements() {
const viewportWidth = document.documentElement.clientWidth;
return [...document.body.querySelectorAll("*")].filter((element) => {
const { left, right, width } = element.getBoundingClientRect();
return width > 0 && (right > viewportWidth + 1 || left < -1);
});
}
console.log(hasHorizontalScroll, findWideElements());
overflow: auto, or a menu positioned off-screen on purpose. Check each result's ancestors before you change its CSS.
Other ways to detect overflow
| Method | Good for | Limits |
|---|---|---|
scrollWidth and clientWidth |
Whether an element's own content is bigger than its box, including truncated text. | Whole numbers only. Ignores overflow to the top and left. |
getBoundingClientRect() |
Fractional sizes, and finding what sticks out of the viewport or a container. | Returns position on screen, so you must compare boxes yourself. It does not know about clipping. |
IntersectionObserver |
Whether an element is actually visible inside a scroll container or the viewport. | Reports visibility, not whether the element's own content overflows. |
Fix the cause
Detection is useful for tooltips and buttons. When the overflow is a layout bug, fix it in CSS.
| Cause | Fix |
|---|---|
| A long unbroken word or URL | overflow-wrap: anywhere; |
| A flex item that refuses to shrink | min-width: 0; on the flex item |
| A grid column sized by its content | minmax(0, 1fr) instead of 1fr |
| An image or video wider than its container | max-width: 100%; height: auto; |
width: 100vw |
100vw includes the scrollbar, so use 100% |
| A wide table or code block | Wrap it in a container with overflow-x: auto; |
Flex items cause many of these surprises. CSS flexbox explained with real layout examples shows how flex items size themselves and why they sometimes refuse to shrink.
Test it
- Open any page and press F12 to open the Console. Paste the helper and the watcher.
- Create a test box that is too narrow for its text, using the first code block below. Then run
getOverflow(box). It reportshorizontal: true. - Widen the box with the second block. Run
getOverflow(box)again. It reportshorizontal: false. - Start watching with the third block. The callback logs once straight away, then again each time you resize the box so that the state flips.
const box = document.createElement("div");
box.style.cssText = "width: 100px; overflow: hidden; white-space: nowrap;";
box.textContent = "This sentence is longer than the box";
document.body.prepend(box);
getOverflow(box); // { horizontal: true, ... }
box.style.width = "600px";
getOverflow(box); // { horizontal: false, ... }
box.style.width = "100px";
watchOverflow(box, (state) => console.log("overflow:", state.horizontal));
// Now change box.style.width and watch the Console.
Troubleshooting
The check always returns false
Look at four things. The element may be inline, so its client size is 0. It may be hidden with display: none. You may be measuring the wrapper when the overflow happens in a child, or the other way around. The check may also run before fonts and images load, so use watchOverflow() instead of a single check.
The check reports overflow by 1px
This is the rounding issue from the edge-cases table. The helper ignores a difference of 1px by default. If your layout needs a stricter check, pass 0 as the tolerance and test at several zoom levels.
The result stops updating after text changes
A one-time check does not know the text changed. Use watchOverflow(), which listens for text and element changes as well as size changes.
ResizeObserver loop error in the Console
ResizeObserver loop completed with undelivered notifications, or the older wording ResizeObserver loop limit exceeded.
The browser prints this when an observer callback changes layout in the same frame that triggered it. It is usually harmless, and the watcher avoids it because the observer callback only schedules a check for the next frame. How to read error messages like a developer explains how to judge whether a Console message needs action.
FAQs
How do I check if text is truncated with an ellipsis?
Compare element.scrollWidth with element.clientWidth. When text-overflow: ellipsis is cutting the text, scrollWidth is larger. The element must be a block-level or inline-block box, not a plain inline element.
What is the difference between clientWidth, offsetWidth and scrollWidth?
clientWidth is the visible width including padding but not the border or scrollbar. offsetWidth adds the border and scrollbar. scrollWidth is the width of the whole content, including the part hidden by overflow. Comparing scrollWidth with clientWidth is the most accurate overflow check.
Why is scrollWidth 1px larger than clientWidth when nothing overflows?
Both properties round to whole numbers, and layouts with fractional sizes or browser zoom can round them in different directions. Treat a difference of 1px as no overflow, or use getBoundingClientRect() when you need fractional values.
How do I detect overflow after a resize or a content change?
Observe the element and its children with ResizeObserver, watch for text and element changes with MutationObserver, and re-check after document.fonts.ready. The watchOverflow() function in this guide combines all three and only calls you when the state changes.
Does the check work on elements with overflow: visible?
Yes. In current browsers, scrollWidth and scrollHeight describe the content size whatever the overflow value is, so the same comparison works for visible, hidden, auto and scroll.
Conclusion
Comparing scrollWidth with clientWidth, and scrollHeight with clientHeight, is the reliable way to detect overflow. Allow 1px for rounding, measure block-level elements that are visible, and use a watcher when the answer can change after load. If the overflow is a bug rather than a feature, fix the CSS cause, and use the detection for the cases where cut-off content is intended.