
Get the width of the scrollbar using only CSS
7/31/24About 2 minCSSArticle(s)blogcss-tip.comcss
Get the width of the scrollbar using only CSS 관련
CSS > Article(s)
Article(s)

Get the width of the scrollbar using only CSS
Using modern CSS features to get the scrollbar width as a CSS variable
Info
You can find a better implementation here

Get the scrollbar width using only CSS
A few lines of code to get the scrollbar width within a CSS variable
"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 CSS-only scrollbar width by t_afif on CodePen.
More CSS Tips
- A decorative line with rounded dashes A few lines of code to create a nice decoratinve line with rounded dashes. August 15, 2024
- A CSS generator for wavy circle shapes Use modern CSS to create a wavy circle shape in no time. August 13, 2024
- Get the width & height of any element without JavaScript Using modern CSS to get the size of any element as CSS variables. July 26, 2024
- Calculate the scroll progress of an arbitrary element A few lines of CSS to get the scroll progress of any element in the page. July 24, 2024

Get the width of the scrollbar using only CSS
Using modern CSS features to get the scrollbar width as a CSS variable