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
- A decorative line with rounded dashes A few lines of code to create a nice decoratinve line with rounded dashes.
- A CSS generator for wavy circle shapes Use modern CSS to create a wavy circle shape in no time.
- Get the width & height of any element without JavaScript Using modern CSS to get the size of any element as CSS variables.
- Calculate the scroll progress of an arbitrary element A few lines of CSS to get the scroll progress of any element in the page.