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.

// 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.

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');
}