clientWidth vs scrollWidth in JavaScript DOM
When working with layout measurements in the JavaScript DOM,
clientWidth, clientHeight,
scrollWidth, and scrollHeight are essential
read-only properties for retrieving element dimensions. While
clientWidth and clientHeight measure the
visible area of an element (the viewport inside its borders),
scrollWidth and scrollHeight measure the
entire content size, including content hidden by overflow. Understanding
these distinctions is critical for implementing custom scrollbars,
infinite scrolling, or dynamic layout adjustments.
clientWidth and clientHeight
The clientWidth and clientHeight properties
represent the inner dimensions of an element’s visible content box.
- What is included: Visible content and padding.
- What is excluded: Borders, margins, horizontal/vertical scrollbars, and any off-screen overflowing content.
- Use case: Measuring the exact visible area available for rendering child elements inside a container.
// Calculation breakdown
clientWidth = CSS width + CSS padding-left + CSS padding-right - vertical scrollbar width (if present)
clientHeight = CSS height + CSS padding-top + CSS padding-bottom - horizontal scrollbar height (if present)scrollWidth and scrollHeight
The scrollWidth and scrollHeight properties
measure the total dimensions of an element’s content, regardless of
whether that content is currently visible on the screen.
- What is included: The entire content area (both
visible and hidden via
overflow: autooroverflow: scroll) and padding. - What is excluded: Borders, margins, and scrollbars.
- Use case: Determining whether an element has overflowing content or calculating how far an element can be scrolled.
If an element has no overflowing content, scrollWidth is
equal to clientWidth, and scrollHeight is
equal to clientHeight.
Key Differences Summary
| Property | Measures | Includes Scrollbars? | Includes Overflow? | Includes Borders? |
|---|---|---|---|---|
clientWidth /
clientHeight |
Visible inner area | No | No | No |
scrollWidth /
scrollHeight |
Total content area | No | Yes | No |
Practical Example: Detecting Overflow
You can compare these properties to programmatically check if an element requires scrolling:
const element = document.querySelector('.container');
const hasVerticalScroll = element.scrollHeight > element.clientHeight;
const hasHorizontalScroll = element.scrollWidth > element.clientWidth;
if (hasVerticalScroll) {
console.log('Vertical overflow detected');
}