Scrollbar Width Checker
Scrollbar Width Checker builds a hidden overflowing box, measures the gap between its outer and inner width, and reports your browser's actual scrollbar width in pixels the moment the page loads. A reading of 0px isn't a bug — it just means you're on macOS or a mobile browser using overlay scrollbars that don't reserve any layout space. This is the exact number that explains why your screen width and browser viewport width rarely match down to the pixel. A quick pass through the viewport size checker catches issues before they become real problems.
Your Result
Ever built a pixel-perfect design only to watch it jolt sideways the moment a scrollbar appears? A reliable scrollbar width checker gives you the exact measurement you need to prevent layout shift before it ever reaches your users — letting you compensate precisely in CSS or scripting rather than guessing at magic numbers. Whether you're fine-tuning a text editing interface, a confined panel, or a full-page design, knowing the width of the scrollbar in the active client is the foundation of stable, professional web design.
What Is Scrollbar Width & Why It Matters — Use a Scrollbar Width Checker
The scrollbar width is the number of pixels consumed by the client's native scrollbar track along the edge of a scrollable element or the viewport width scrollbar zone. On most Windows systems, this value sits at approximately 15–17px for a side bar, while macOS uses overlay scrollbars that hover above content and report a width of 0px when not active. Linux distributions vary depending on the desktop environment and GTK theme in use. These differences make consistent rendering a genuine challenge in frontend web development.
How the Scrollbar Affects Page Structure and Content Space
When a scrolling container switches from overflow: hidden to overflow: auto — for instance on an overflow:auto hover pattern — the client inserts the scrollbar inside the element's content box. This trims pixels off the available content width, causing text to reflow, columns to shift, and margins to recalculate. The effect is a visible structure width shift that breaks the user's reading experience. Reserving the correct scrollbar placeholder width in advance is the only reliable way to avoid this jarring movement, and it requires knowing the exact scrollbar thickness for each platform and operating system.
The modern scrollbar-gutter attribute offers a CSS-native remedy: scrollbar-gutter: stable reserves space for the scrollbar even when it is not yet visible, so that scrollbar appears or disappears without causing reflow. When combined with scrollbar-gutter stable both-edges, the client adds equal whitespace on both sides of the scrolling element, maintaining visual balance in web design. However, scrollbar-gutter requires overflow: auto or overflow-y: auto to be set on the same element.
Scrollbar Width Across Platforms and Operating Systems
No single, consistent scrollbar size exists across all platforms. Here is a quick reference for typical scrollbar thicknesses:
- Chrome scrollbar width (Windows): ~17px classic, 0px overlay on macOS
- Firefox scrollbar width: historically 17px on Windows; Firefox introduced
scrollbar-widthas the first major platform to do so - Edge scrollbar width: matches Chromium behaviour — ~17px on Windows, overlay on macOS
- Safari scrollbar width: 0px overlay by default on macOS; 17px when the macOS "Always show scrollbars" usability setting is active
- Opera scrollbar width: follows Chromium — ~17px on Windows
- Mobile browser scrollbar: typically 0px because mobile clients use overlay scrollbars that do not affect page structure
On macOS, the operating system controls whether scrollbars are overlay or classic, so the same client can report 0 or 17px depending on user preferences. On Linux, the desktop environment's GTK or Qt theme controls scrollbar size. This is why a scrollbar detector that runs at runtime — rather than a hardcoded integer — is always more reliable for responsive, production-grade designs.
CSS scrollbar-width Property: Syntax, Values & Formal Definition
The scrollbar-width style attribute is part of the CSS Working Group's Scrollbars Module Level 1 — a specification that is still a work in progress, though its core values have reached Baseline 2024 (Newly available) status. It controls the thickness or desired thickness of the scrollbar rendered on a scrolling element, offering a standardised, author-set alternative to the vendor-prefixed -webkit-scrollbar pseudo-element approach used historically in Chrome and Safari.
Getting Started & Accepted Values for scrollbar-width
The formal syntax for the rule is:
scrollbar-width = auto | thin | noneThe rule accepts the following values (referred to as preset values in the specification debate, as a variable <length> length value argument has not yet been finalised):
auto- scrollbar width auto — the default. The client renders its standard scrollbars as defined by the user agent. Most desktop platforms will show the platform's full-size scrollbar. This is the initial value.
thin- scrollbar-width thin — instructs the client to use thinner scrollbars when the platform supports them. In Firefox, this renders a noticeably narrower track; other clients may interpret this keyword differently or fall back to
autosizing. none- scrollbar-width none — hides the scrollbar completely. The scrolling element retains full scrollability: users can still scroll via wheel, keyboard, or touch, but the visual scrollbar track and thumb are not rendered. This preserves element scrollability while reclaiming space.
There is ongoing debate in the CSSWG and the broader web standards community about whether a <length> width argument will eventually be added, which would allow you to specify an exact pixel width as a length value. For now, you are limited to these three keyword style rule values.
Scrollbar Sizes Comparison Across Values
The following table illustrates the effective scrollbar size for each value across major clients, giving you a practical sizes comparison reference for scrollbar styling decisions:
| Value | Chrome (Windows) | Firefox (Windows) | Safari (macOS overlay) | Edge (Windows) |
|---|---|---|---|---|
auto | ~17px | ~17px | 0px (overlay) | ~17px |
thin | ~6px | ~6px | 0px (overlay) | ~6px |
none | 0px | 0px | 0px | 0px |
The rule applies to all elements that can display scrollbars — that is, any scrolling element whose overflow is auto, scroll, or overlay. It is not inherited by child elements, its computed value is the specified keyword, and its animation type is discrete.
Formal Rule Definition & Specification Reference
For developers who need to reason about the css scrollbar rule in a specification context, here is the complete formal definition table as defined in the CSS Overflow Module / Scrollbars Module Level 1:
| Property | Value |
|---|---|
| Initial value | auto |
| Applies to | Scrolling boxes (elements with overflow auto, scroll, or overlay) |
| Inherited | No |
| Computed value | As specified keyword |
| Animation type | Discrete |
| Specification | CSS Scrollbars Module Level 1 — W3C Working Draft |
The formal syntax as ratified by the standards body is scrollbar-width: auto | thin | none. The specifications note that clients reaching Baseline 2024 status must support at minimum the three keyword values. The specification draft also defines the companion scrollbar-color rule, allowing scrollbar customization of both track and thumb colours. Together, scrollbar-width and the color companion form the standard style surface for scrollbar ui styling.
Checking Browser Scrollbar Width with JavaScript Runtime Detection
Because the browser scrollbar width varies by operating system and user agent, you cannot hardcode a reliable pixel value at compile time. Instead, a lightweight scripted scrollbar detector reads the actual width at runtime. The two most widely used page properties for this are innerWidth and clientWidth.
Using window.innerWidth and document.body.clientWidth to Measure the Scrollbar
innerWidth: The read-only
Windowattributewindow.innerWidthreturns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present.
clientWidth on the top-level element: When
clientWidthis used on the top-level element (the<html>element), the viewport width scrollbar-excluded measurement is returned.
The calculation is straightforward:
$$\text{scrollbar width} = \text{window.innerWidth} - \text{document.body.clientWidth}$$This formula subtracts the content-only page width from the total window width (which includes the vertical bar), leaving you with just the scrollbar's pixel contribution. On a standard Windows desktop this typically returns 17; on macOS with overlay scrollbars it returns 0.
// Step 1. Calculate the scrollbar width at runtime
const scrollbarWidth = window.innerWidth - document.body.clientWidth;
console.log(scrollbarWidth); // e.g. 17 on Windows, 0 on macOSAn alternative approach uses document.documentElement.offsetWidth instead of the body client measurement, which is more reliable when the body element has a max-width set:
// Alternative using document.documentElement.offsetWidth
const scrollbarWidth = window.innerWidth - document.documentElement.offsetWidth;
console.log(scrollbarWidth);For fractional scrollbar width precision (e.g. 16.8px rather than a rounded integer), a more robust technique uses document.createElement div appended to the page and measured with getComputedStyle:
// Fractional-precision scrollbar measure
const scrollDiv = document.createElement('div');
scrollDiv.style.height = '0px';
scrollDiv.style.width = '100%';
scrollDiv.style.visibility = 'hidden';
document.body.appendChild(scrollDiv);
const clientWidth = Number(
getComputedStyle(scrollDiv).width.replace(/[^\d\.]/g, '')
);
document.body.removeChild(scrollDiv);
const scrollbarPrecise = document.documentElement.offsetWidth - clientWidth;
console.log(scrollbarPrecise); // e.g. 16.8For WebKit/Blink clients only, a one-liner using the scrollbar pseudo element is sometimes used: getComputedStyle(document.documentElement, '::-webkit-scrollbar').width. Note that this relies on the -webkit-scrollbar (or webkit scrollbar) pseudo-element and does not work in Firefox. Modern Chrome versions may also return auto rather than a pixel value, making it unreliable.
Setting a CSS Custom Property for Scrollbar Width — Step 2
Once you have the scrollbar measure as a numeric value, the most powerful pattern in modern web development is to inject it as a css variable on the document root. This makes the value available everywhere in your stylesheet, giving you a live, platform-specific token for structure compensation.
// Step 2. Inject scrollbar width as a CSS custom property
document.body.style.setProperty(
'--scrollbar-width',
(window.innerWidth - document.body.clientWidth) + 'px'
);
// OR using the html element for document-level scrollbars:
document.documentElement.style.setProperty(
'--scrollbar-width',
(window.innerWidth - document.documentElement.offsetWidth) + 'px'
);A useMemo scrollbar pattern is available in React (react scrollbarWidth) for memoising the calculation and avoiding repeated page operations across renders. The export function scrollbar pattern from the @xobotyi/scrollbar-width npm module is a ready-made, lightweight tool that encapsulates this exact logic.
Applying Scrollbar Width in CSS with Custom Properties & calc()
With --scrollbar-width injected on the <body> or :root, your stylesheet can reference it in any calculation. This is the complete solution to use within CSS for preventing structure jumps caused by a scrollbar change.
The calc(100vw - (100vw - 100%)) Pure CSS Formula
A pure css solution that requires no scripting at all exploits the difference between 100vw (which includes the scrollbar width) and 100% (which excludes it for block-level elements). The expression:
resolves by the mathematical identity (x − (x − 100%)) = 100%, but with the important side effect that the client evaluates 100vw - 100% as the scrollbar thickness at parse time, meaning the calc 100vw 100% technique effectively reserves exactly the right amount of space. This makes it useful for margin right scrollbar compensation without a scripting dependency.
/* Pure CSS: reserve scrollbar space with calc(100vw - (100vw - 100%)) */
.content-container {
width: calc(100vw - (100vw - 100%));
/* resolves to available content width, excluding scrollbar */
}Complete CSS Solution for Structure Compensation Using CSS Variable Scrollbar
When you combine the scripted detection step with a css custom property, the result is a robust css variable scrollbar pattern:
/* Use the injected --scrollbar-width CSS variable for structure compensation */
body {
width: calc(100vw - var(--scrollbar-width));
}
/* Prevent paragraph margin shift when scrollbar appears */
div p {
margin: 20px calc(20px + var(--scrollbar-width)) 20px 50px;
}
div:hover p {
margin: 20px; /* scrollbar now present, margin is symmetrical */
}
/* Bonus tip: expand a child element to full page width
while accounting for the scrollbar */
.full-bleed-child {
width: calc(100vw - var(--scrollbar-width));
margin-left: calc(-50vw + 50% + (var(--scrollbar-width)) / 2);
}For 2023 and later, container queries unlock an even cleaner approach. By applying container-type: inline-size to a parent element, you can reference 100cqw (100% container query width) to get the available content width of that specific container — allowing precise padding scrollbar adjustment on non-body elements without referencing the global page width. This interaction with container-type inline-size is the core of the modern scoped sizing pattern:
/* 2023: Scoped sizing approach for non-body scrolling containers */
div.demo {
width: 400px;
height: 200px;
overflow: hidden;
container-type: inline-size;
}
div.demo:hover {
overflow: auto;
}
div.demo p {
/* margin-right adjusts dynamically based on container's scrollbar */
margin: 20px calc(40px - (100cqw - 100%)) 20px 20px;
}You can also use a pure CSS-only :root trick that combines container-type: inline-size with overflow-x: clip to derive the --scrollbar-width entirely in CSS, with no scripting at all: --scrollbar-width: calc(100vw - 100cqw). Note: this only works if there are no other scoped container types declared on the page.
Markup Implementation: In-Page Setup for Scrollbar Detection
Here is a full working example showing how your scrollbar width checker integrates across the three layers of a web page — markup structure, style rules, and scripted detection — using the classic scrollbar measure technique with offsetWidth and clientWidth.
In HTML
Your markup needs a scrolling container to demonstrate the effect, plus a display element to show the detected value. The key structural requirement is that the scrolling container uses overflow-y: scroll or overflow: auto so that the client allocates space for the side scrollbar.
<!-- In HTML: scrollbar width checker live example -->
<div class="scrollable-demo">
<p>Long content that triggers a vertical scrollbar...</p>
</div>
<p>Detected scrollbar width: <span id="scrollbar-display"></span></p>In CSS
The style rules set up your scrolling element with a fixed width and height, and an overflow-y scroll declaration to ensure the vertical bar is always rendered — critical for consistent detection. You can also pre-declare the --scrollbar-width CSS custom property as a fallback. Note the background color is set to aid visual testing.
/* In CSS: set up the scrollable container */
:root {
--scrollbar-width: 0px; /* fallback before JS runs */
}
.scrollable-demo {
width: 300px;
height: 200px;
overflow-y: scroll;
background: #f4f4f4;
padding: 1rem;
}
/* Hide scrollbar visually but preserve scrollability */
.scrollable-element {
scrollbar-width: none;
-ms-overflow-style: none; /* IE/Edge legacy */
}
.scrollable-element::-webkit-scrollbar {
display: none; /* Chrome, Safari, Opera */
}
/* Structure compensation using the injected variable */
body {
width: calc(100vw - var(--scrollbar-width));
}In JavaScript
The scripted snippet creates a temporary div, forces it to scroll, measures the scrollDiv offsetWidth minus scrollDiv clientWidth (the offsetwidth clientwidth subtraction), and then removes it — leaving no trace in the page tree.
// In JavaScript: detect and inject scrollbar width
document.addEventListener('DOMContentLoaded', function () {
// Method 1: innerWidth minus clientWidth (simplest)
const scrollbarWidth = window.innerWidth - document.body.clientWidth;
// Method 2: temporary div technique (more accurate for fractional widths)
const scrollDiv = document.createElement('div');
scrollDiv.style.overflow = 'scroll';
scrollDiv.style.position = 'absolute';
scrollDiv.style.top = '-9999px';
document.body.appendChild(scrollDiv);
const scrollbarWidthAlt = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
// Display result
document.getElementById('scrollbar-display').textContent =
scrollbarWidth + 'px';
// Inject as CSS custom property
document.body.style.setProperty(
'--scrollbar-width',
scrollbarWidth + 'px'
);
console.log('Browser scrollbar width:', scrollbarWidth + 'px');
});A jquery scrollbar equivalent using the same offsetWidth clientWidth principle is also common in legacy codebases: var width = div.prop('offsetWidth') - div.prop('clientWidth'); — though modern projects should prefer the vanilla scripting approach shown above.
Using the scrollbar-width npm Module for Scripted Projects
If you'd rather reach for a battle-tested, open source scrollbar tool than maintain your own detection snippet, the @xobotyi/scrollbar-width npm module offers a lightweight, framework-agnostic solution with multi-platform support. It's an ideal choice for frontend frameworks where a consistent, memoised scrollbar measure is needed.
Setup & Getting Started with the scrollbar-width Module
# Setup via npm
npm install @xobotyi/scrollbar-width
# Or via yarn
yarn add @xobotyi/scrollbar-width// Import and initial use
import { scrollbarWidth } from '@xobotyi/scrollbar-width';
// For most platforms will return 17 on Windows
// Returns 0 for SSR (server-side rendering) environments
// Returns undefined if called before the page tree is ready
const width = scrollbarWidth();
console.log(width); // e.g. 17Module Stats, Repository Files, & Version History
The module is actively maintained as an open source project. The following table summarises its community metrics, which you can verify against the latest commit on the repository:
| Metric | Value (approximate) |
|---|---|
| Stars | ~150+ |
| Forks | ~20+ |
| Watchers | ~5 |
| Contributors | ~5 |
| Latest release | Check npm for current version |
| Releases | See GitHub releases page |
| Bundles | 1 (ESM + CJS) |
The module is published under a permissive licence, includes a code of conduct, and its repository files include both ESM and CommonJS builds, TypeScript type definitions, and a test suite. The latest commit history shows active maintenance in response to client behaviour changes. For related projects, consider also scrollbar-gutter-based solutions and the modern CSS-only scoped query approach described above.
Platform Support & Compatibility for scrollbar-width in CSS
Firefox pioneered the scrollbar-width style rule, shipping it well before other vendors. As of Baseline 2024, the rule is classified as "Newly available" — meaning it is supported across the latest stable release of every major client, making it safe for production use without a polyfill in most contexts. Legacy versions from before 2023 may still appear in some analytics, so a graceful degradation strategy is recommended.
Updated Compatibility Table for 2023 and Onwards
| Browser | Version Added | Notes |
|---|---|---|
| Firefox | 64 | First implementer; reference client for the specification |
| Chrome | 121 | Baseline 2024; no vendor prefix required |
| Edge | 121 | Chromium-based; same as Chrome |
| Safari | 17.4 (macOS 14.4) | Late adopter; now fully supported |
| Opera | 107 | Chromium-based; follows Chrome |
- Firefox is the key reference client — it defined the rule's initial behaviour and the two-value syntax proposal.
- Baseline 2024 status confirms compatibility across the modern client landscape without vendor prefix requirements.
- In 2023, the interaction between
scrollbar-widthand scoped sizing queries became practically significant: when a container usescontainer-type: inline-size, thescrollbar-widthrule can affect the container's available inline size reported via100cqw. - The legacy -ms-overflow-style rule (Internet Explorer / old Edge) served a similar purpose but has a different syntax. For completeness, you can include it alongside
scrollbar-width: nonefor maximum multi-platform scrollbar compatibility. - On clients that do not yet support
scrollbar-widthin CSS, the scriptedwindow.innerWidth - document.body.clientWidthapproach remains a reliable fallback.
Sizing Scrollbars & Usability Considerations
The sizing scrollbars use case is one of the primary motivations behind the scrollbar-width rule. Particularly on pages with limited space or a compact container, reducing scrollbar thickness from the default auto to thin can give your content meaningful breathing room — especially in a text editing interface where a textarea scrollbar competes for space with the text itself. The specification states:
"allows authors to reserve space for the scrollbar, preventing unwanted layout changes as the content grows while also avoiding unnecessary visuals when scrolling isn't needed."
However, the most commonly misused value is none. Setting scrollbar-width: none (or the pattern display: none scrollbar via ::-webkit-scrollbar { display: none } and -ms-overflow-style: none) on a scrolling element hides the scrollbar completely while preserving scrollability. Users can still scroll via wheel, touch swipe, or keyboard — but they receive no visual affordance that the content is scrollable. This creates scrollbar visibility and usability problems:
- Screen reader users and keyboard-only users depend on visible scrollbars as UI cues that a region has additional content below the fold.
- Users unfamiliar with trackpad or scroll wheel gestures may not discover keyboard alternatives.
- Hiding scrollbars on mobile where overlay scrollbar behaviour already makes them intermittent can further reduce discoverability.
- WCAG success criterion 2.1.1 (Keyboard) and 1.3.1 (Info and Relationships) are indirectly impacted when scroll regions are invisible.
A better pattern for scrollbar reserve space without sacrificing scrollbar visibility is scrollbar-gutter: stable. This style rule reserves a scrollbar placeholder in the design even when no scrollbar is currently shown, preventing scrollbar disappearing-and-reappearing jumps. Combine it with scrollbar-gutter stable on a fixed div scrollbar container or a full-page design to achieve a stable, inclusive result:
/* Reserve scrollbar space without hiding it */
.scrollable-container {
overflow: auto;
scrollbar-gutter: stable;
}
/* scrollbar-width: thin saves space in a compact container
without removing the scrollbar entirely */
.narrow-panel {
overflow-y: auto;
scrollbar-width: thin;
scrollbar-gutter: stable;
width: 200px;
}
/* Hide scrollbar while keeping scroll — use with caution */
.scrollable-element {
overflow-y: scroll;
scrollbar-width: none;
}Common Questions About Scrollbar Size Detection and CSS scrollbar-width
Frequently Asked Developer Questions
What is the default scrollbar width in browsers?
The default value of scrollbar-width is auto, which instructs the client to render its standard scrollbars. On Windows, the standard scrollbar is approximately 17px wide. On macOS with the default "Automatic" scroll indicator preference, overlay scrollbars have a width of 0px (they appear on top of content when scrolling, then fade). With "Always show scroll bars" enabled in macOS settings, they become ~15–17px. Linux scrollbar sizes depend on the desktop theme. This tool, when run at runtime, will always give you the accurate value for the active session.
How do I detect scrollbar width with JavaScript?
The cleanest modern approach uses window.innerWidth - document.body.clientWidth. For body elements with max-width, prefer subtracting the root offset width from the window inner width. For fractional precision, use style computation on a temporary full-width element. All three methods subtract a width that includes the scrollbar from one that excludes it, revealing the scrollbar's pixel contribution. window.visualViewport.width is another option: it returns the visual viewport width scrollbar-excluded measurement.
How do I hide a scrollbar but keep scroll functionality?
Use the combined pattern: set scrollbar-width: none in CSS for Firefox and modern clients, -ms-overflow-style: none for legacy Edge/IE, and ::-webkit-scrollbar { display: none; } for Chrome, Safari, and Opera. The element will remain scrollable via keyboard, wheel, and touch. Be aware of the inclusive design implications — users need alternative affordances to discover the scrollable region. Consider whether scrollbar-width: thin with scrollbar-gutter: stable is a less harmful alternative for your use case.
What does Baseline 2024 mean for scrollbar-width?
Baseline 2024 ("Newly available") means the scrollbar-width style rule reached full support across Chrome, Edge, Firefox, and Safari within 2024. Prior to Chrome 121 and Safari 17.4, the rule was a Firefox-only feature. Now that it has Baseline status, you can use it in production without a scripted polyfill for users on current client versions. Older clients still require fallback strategies — either the scripted detection approach or the -webkit-scrollbar pseudo-element route for WebKit-based clients.
Does scrollbar-width work with container queries?
Yes — this is one of the most important frontend developments of 2023. When a container uses container-type: inline-size, the client reports the container's available content width via the inline size unit. If scrollbar-width is set to auto or the client shows a classic scrollbar, the scrollbar's width is subtracted from the container's inline size before the size unit is calculated. This means you can write margin: 20px calc(40px - (100cqw - 100%)) 20px 20px to compensate precisely for the scrollbar inside a fixed-width container, entirely in CSS — no scripting required. See the specification for container-type inline-size for full details.
Advanced Techniques: Scrollbar Customization & Vendor Prefixes
In standard web CSS, the vendor-specific -webkit-scrollbar family of pseudo-elements predates the specification's scrollbar-width rule by many years and provides much finer-grained scrollbar customization:
::-webkit-scrollbar— targets the scrollbar track area::-webkit-scrollbar-thumb— targets the draggable scrollbar thumb::-webkit-scrollbar-track— targets the scrollbar track background color areams-overflow-style— the Internet Explorer/old Edge equivalent for hiding scrollbarsscrollbar-color— the modern companion rule, controlling thumb and track colours
The css overflow module (CSS Overflow Module Level 3 and Level 4) defines the broader context for all scrollbar-related rules, including overflow auto, overflow hidden, overflow scroll, and the newer overflow-y scroll single-axis control. The scrollbar-gutter rule is defined in this same specification, providing the scrollbar reserve space mechanism. Scrollbar-gutter stable is now the recommended way to prevent layout shift caused by a scrollbar appearing or disappearing — a significant improvement over the scripted workarounds that frontend developers relied on for years.
For any web design or UI work where responsive designs need to account for scrollbar presence across multiple breakpoints, combining scrollbar-gutter: stable for modern clients with the scripted --scrollbar-width variable injection as a fallback gives you the most dynamic scrollbar width handling available today. This dual strategy is the consensus scroll behavior recommendation from the Stack Overflow community, the MDN Web Docs team, and the CSS-Tricks developer audience alike.
Frequently Asked Questions
- What is the scrollbar width in most browsers?
- In most desktop browsers like Chrome, Firefox, and Edge, the default scrollbar width is 15–17 pixels. On macOS with overlay scrollbars enabled, the width is effectively 0px because scrollbars float over content without taking up layout space.
- How do I detect scrollbar width with JavaScript?
- The most reliable method is to compare window.innerWidth with document.body.clientWidth — the difference is the scrollbar width. Another approach creates a hidden div with overflow: scroll, then compares its offsetWidth to its clientWidth to get the scrollbar thickness.
- What does the CSS scrollbar-width property do?
- The CSS scrollbar-width property controls the thickness of scrollbars on an element. It accepts three keyword values: auto (the default browser scrollbar), thin (a narrower scrollbar), and none (hides the scrollbar while keeping scroll functionality).
- Is scrollbar-width: none the same as overflow: hidden?
- No. Setting scrollbar-width: none hides the scrollbar visually but the element remains scrollable — users can still scroll via touch, keyboard, or programmatic scroll. overflow: hidden actually disables scrolling entirely.
- Which browsers support the CSS scrollbar-width property?
- As of 2024, scrollbar-width is supported in Firefox (since 2019), Chrome/Edge/Opera (Chromium 121+), and Safari 18+. It is now considered baseline-available across major browsers. Always check caniuse.com for the latest compatibility data.
- Why does scrollbar width affect my CSS layout?
- On most desktop operating systems, scrollbars are 'classic' and occupy layout space, reducing the available content width. When a scrollbar appears (e.g., on overflow: auto elements), content shifts inward by the scrollbar's width, potentially breaking layouts or wrapping text unexpectedly.
- How can I prevent layout shift when a scrollbar appears?
- You can use overflow-y: scroll to always show the scrollbar (even when not needed), use scrollbar-gutter: stable in modern browsers, or account for the scrollbar width dynamically in CSS with calc(). Setting a consistent padding on the body matching the expected scrollbar width also works.
- What is scrollbar-gutter and how does it relate to scrollbar width?
- The scrollbar-gutter CSS property reserves space for the scrollbar even when it isn't displayed, preventing layout shifts. It is closely related to scrollbar width — by reserving exactly the scrollbar-width amount of space, content alignment stays consistent whether or not a scrollbar is visible.