I am working on creating a dynamic progress bar with inverted text color using only CSS.
To see examples of what I am trying to achieve, you can refer to the following links.
Inverted Colors CSS progress bar
https://i.sstatic.net/VSs5V.png
The issue I am facing is that the progress bars in the examples provided have fixed widths. I want the progress bar to be of a width of 100% or some other relative length. It's proving difficult to modify the existing examples to fit my requirements without using JavaScript.
You can see my unsuccessful attempt here. Can you help adjust the implementation so that the progress bar supports relative widths like 50%?
Here is the code snippet. Thanks to @TheThirdMan.
body {
background-color: #000;
}
h1 {
text-align: center;
font-family: "Trebuchet MS", Helvetica, sans-serif;
font-weight: normal;
margin: 50px 0 0;
color: #fff;
}
.progress {
position: relative;
border: 0;
width: 500px;
height: 40px;
line-height: 40px;
margin: 100px auto;
font-family: arial, sans-serif;
font-weight: bold;
font-size: 30px;
background-color: #07A4DD;
border-radius: 40px;
overflow: hidden;
}
.progress .progress-text {
position: absolute;
top: 0;
width: 500px;
text-align: center;
color: #fff;
font-variant: small-caps;
}
.progress .progress-bar {
height: 100%;
overflow: hidden;
width: 54%;
background-color: #fff;
border-radius: inherit;
overflow: hidden;
position: relative;
-webkit-animation: animate 4s;
animation: animate 4s;
}
.progress .progress-bar .progress-text {
color: #07A4DD;
}
@-webkit-keyframes animate {
0% {
width: 0%;
}
}
@keyframes animate {
0% {
width: 0%;
}
}
<h1>Flexible CSS progress bar with inverted colors</h1>
<div class="progress">
<div class="progress-text">Progress</div>
<div class="progress-bar">
<div class="progress-text">Progress</div>
</div>
</div>
Thank you to @AndrewBone for the suggestion, but I have reasons for not using `vw` in this project:
- We previously used `vw` for other projects, but it was not supported on some Android devices so we had to abandon it.
- In many cases, the parent of `.progress` may not be proportionate to the viewport's width.
Here is my attempt. It is similar to the concept of CSS Progress bars.
The idea behind it is as follows:
- Both `.progress-text` elements are absolutely positioned and have the same width as `.progress`.
- The first `.progress-text` is white and acts as a background within `.progress`.
- The second `.progress-text` is blue and is clipped by `.progress-bar`.
This leads to:
- `.progress-bar` needs to be relatively positioned to clip `.progress-text`.
- `.progress-text` cannot obtain the width of `.progress` as it is absolutely positioned to `.progress-bar` and not `.progress`.
Therefore:
- If `.progress` has a fixed width (e.g. `$bar-width: 500px`), I can center `.progres-text` by setting its width to match that of `.progress`.
- If `.progress` has a relative width (e.g. `$bar-width: 50%`), what steps should I take to make it work?