How can I create a CSS-only animated progress bar with percentage label?
Davide S
davide s profile pic

To create a CSS-only animated progress bar with a percentage label, you can utilize CSS keyframes animations and pseudo-elements. Here's a step-by-step guide on how to achieve this: 1. HTML Markup: Start by creating the HTML structure for the progress bar and percentage label:

1
2
3
4
5
  <div class="progress-bar">
     <div class="progress" style="width: 70%;"></div>
     <span class="percentage-label">70%</span>
   </div>
   

In this example, we have a parent container with the class"progress-bar", which holds the progress bar and percentage label. The progress bar itself is represented by adiv element with the class"progress", and the percentage label is aspan element with the class"percentage-label". Thestyle attribute is used to set the initial width of the progress bar. 2. CSS Styling: Apply CSS styles to create the animated progress bar and percentage label:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 .progress-bar {
     width: 200px;
     height: 20px;
     border: 1px solid #ccc;
     position: relative;
   }

   .progress {
     height: 100%;
     background-color: #0f9d58;
     position: relative;
     animation: progressAnimation 2s ease-in-out forwards;
   }

   .percentage-label {
     position: absolute;
     top: 50%;
     left: 50%;
     transform: translate(-50%, -50%);
   }

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

In this example, we style the.progress-bar container with a fixed width and height, and a border for visual distinction. The.progress class represents the progress bar itself, with a height of 100% and a background color of your choice (in this case,#0f9d58). Theanimation property is used to apply theprogressAnimation keyframe animation to the progress bar, setting a duration of 2 seconds and easing the animation in and out. The.percentage-label class is positioned absolutely inside the.progress-bar container, withtop: 50% andleft: 50% to center it. Thetransform property withtranslate(-50%, -50%) is used to ensure proper centering. The@keyframes rule defines theprogressAnimation animation, transitioning the width of the progress bar from0% to100% over the duration of the animation. 3. Customize the Styling: Customize the CSS styles as per your design requirements. You can adjust the width, height, colors, and animation duration to fit your needs. By following these steps and customizing the CSS styles within the.progress-bar,.progress, and.percentage-label selectors, you can create a CSS-only animated progress bar with a percentage label. The progress bar will animate smoothly from0% to100%, and the percentage label will remain centered within the progress bar, indicating the progress of the task or process.