Get the scrollbar width using only CSS
Do you want to know the scrollbar width? It's possible using only CSS and a few lines of code! You can get the pixel value within a CSS variable and use it everywhere.
As a bonus, you can also have an integer value!
@property --scrollbar {
syntax: "<length>";
inherits: true;
initial-value: 0px;
}
html {
container-type: inline-size;
}
body {
--scrollbar: calc(100vw - 100cqw);
/*
100cqw is the html width
100vw is the viewport width
the difference is the scrollbar width 🤩
*/
}
/* As a bonus, you can have an interger value and show it */
body:before {
content: counter(val) "px";
counter-reset: val tan(atan2(var(--scrollbar),1px));
}
Tested on Chrome
See the Pen CSS-only scrollbar width by Temani Afif (@t_afif) on CodePen.