Skip to main content
CSS Tip

Get the width of the scrollbar using only CSS

"What is the width of the scrollbar?" A question we can answer using a few lines of modern CSS! No need for JavaScript and you get the value as a CSS variable defined at :root level.

@property --x {
syntax: "<number>";
inherits: true;
initial-value: 1;
}
html {
/* --w will contain a unitless value of the scrollbar width */
--w: calc(100cqw*var(--x)/1px);
timeline-scope: --x;
animation: --x linear;
animation-timeline: --x;
animation-range: entry 100% exit 100%;
}
html:before {
content: "";
position: fixed;
left: 0;
aspect-ratio: 1;
overflow: hidden;
scrollbar-gutter: stable;
view-timeline: --x inline;
}
@keyframes --x {to {--x:0}}

Chrome-only for now

See the Pen CSS-only scrollbar width by Temani Afif (@t_afif) on CodePen.

More detail: frontendmasters.com/blog/how-to-get-the-width-height-of-any-element-in-only-css

Related: https://codepen.io/propjockey/pen/ogzovYg


More CSS Tips