Calculate the scroll progress of an arbitrary element
The same code of the previous trick can also be used to get the scroll progress of any element on the page. The only difference is the use of self
inside the scroll()
value.
@property --s {
syntax: '<integer>';
inherits: true;
initial-value: 0;
}
.scroll {
animation: scroll 1s linear;
animation-timeline: scroll(self);
}
@keyframes scroll {
to {--s: 100}
}
.scroll:before {
content: "Scroll Progress: " counter(s) "%";
counter-reset: s var(--s);
}
See the Pen CSS only scroll progress II by Temani Afif (@t_afif) on CodePen.
More CSS Tips
- Get the width of the scrollbar using only CSS Using modern CSS features to get the scrollbar width as a CSS variable.
- Count the number of lines inside a text A CSS-only solution to count the lines of text.
- Manual typography using Scroll-driven animations Use a range slider to manually adjust the font-size of your website (100% CSS).
- Typed CSS variables using @property Upgrade your CSS variables by registring them using the @property.