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.
More CSS Tips
- Full-bleed layout with modern CSS A few lines of code to make a section extend to the edges of the screen.
- How to correctly use steps() with animations The default behavior of steps() is not intuitive so learn how to use it correctly.
- Indent each line of your text A new value of text-indent that allows you to indent each line of text.
- Select the last occurrence of an element in the whole document Select the last occurrence of any element in the whole document.