Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

CSS-Only Reading Progress Bar

To build a reading progress bar, the one that shows the progress of the user reading the article as they scroll down, it’s hard to not think about JavaScript. But, it turns out, you can build a reading progress bar using pure CSS as well.

The animation-timeline property

Essentially, a new experimental CSS property called animation-timeline lets you specify the timeline that is used to control the progress of a CSS animation. And this is what we’re going to use to build our reading progress bar.

First up, we need to define a div element that will act as a progress bar. We will wrap this div using a container which will be fixed to the top of the viewport. This will ensure that the progress bar is always visible to the user as they scroll down the page.

<div class="progress-bar-container">
    <div class="progress-bar"></div>
</div>
<div class="content">
    <!-- content goes here -->
</div>

Next, we will define the styles for the progress bar. We will set the progress-bar-container to be fixed to the top of the viewport and adjust its background color which will always be visible to the user. We will also set the progress-bar to be 100% wide.

.progress-bar-container {
    position: fixed;
    top: 0px;
    width: 100%;
    background: #6c2fa2;
    z-index: 999;
}

Now, to animate the progress bar, we will use a different background color for progress-bar and set its height to 7px. We will also set the animation-name to width which essentially animates the width of the progress bar from 0 to 100%.

Finally, we will set the animation-timeline to scroll(y) which ties the animation timeline to the vertical scroll position of the viewport. This will ensure that the progress bar animates as the user scrolls down the page.

.progress-bar {
    height: 7px;
    background: #e131ff;
    animation-name: width;

    /* animation timeline is tied to vertical scroll position */
    animation-timeline: scroll(y);
}

@keyframes width {
    from { width: 0 }
    to   { width: 100% }
}

And that’s it! You can see it in action below.

The demo

See the Pen Untitled by Amit Merchant (@amit_merchant) on CodePen.

In closing

Since the animation-timeline property is still in the experimental phase, it’s not supported by all the browsers (Firefox and Safari to be precise) yet.

You can check the browser compatibility and use it accordingly.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?