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 --w {
syntax: "<integer>";
inherits: true;
initial-value: 0;
}
@property --_x {
syntax: "<number>";
inherits: true;
initial-value: 0;
}
@property --_w {
syntax: '<length>';
inherits: true;
initial-value: 100vw;
}
html {
/* --w will contain the width in pixel of the scrollbar
it's a unitless value (integer) */

--w: calc(tan(atan2(var(--_w),1px)) - 1/(1 - var(--_x)));
timeline-scope: --cx;
animation: x linear;
animation-timeline: --cx;
animation-range: entry 100% exit 100%;
}
html:before {
content:"";
position: fixed;
left: 0;
width: 1px;
view-timeline: --cx inline;
}
@keyframes x {to{--_x:1}}

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


More CSS Tips