CSS-Only Reading Progress Bar

By admin
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
ORDINAL

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%
PERCENT

wide.

.progress-bar-container { position : fixed ; top : 0px ; width :

100%
PERCENT

; background : #

6c2fa2
MONEY

; z-index :

999
CARDINAL

; }

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%
PERCENT

.

Finally, we will set the animation-timeline to

scroll(y
ORG

) 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
CARDINAL

; background : #e131ff ; animation-name : width ; /* animation timeline is tied to vertical scroll position */ animation-timeline : scroll ( y ); } @keyframes width { from { width :

0
CARDINAL

} to { width :

100%
PERCENT

} }

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

The demo

See the Pen Untitled by

Amit Merchant
PERSON

(@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
ORG

and

Safari
ORG

to be precise) yet.

You can check the browser compatibility and use it accordingly.