
Get the scrollbar width using only CSS
11/14/24About 1 minCSSArticle(s)blogcss-tip.comcss
Get the scrollbar width using only CSS 관련
CSS > Article(s)
Article(s)

Get the scrollbar width using only CSS
A few lines of code to get the scrollbar width within a CSS variable
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 CSS-only scrollbar width by 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. November 26, 2024
- How to correctly use steps() with animations The default behavior of steps() is not intuitive so learn how to use it correctly. November 18, 2024
- Indent each line of your text A new value of text-indent that allows you to indent each line of text. November 04, 2024
- Select the last occurrence of an element in the whole document Select the last occurrence of any element in the whole document. October 31, 2024

Get the scrollbar width using only CSS
A few lines of code to get the scrollbar width within a CSS variable