Text blended over background color
I'm trying to style a progress bar which looks like this:
The left part can have different colors (green, orange, etc) and I want the text to change color according to the background underneath. Ideally, it should be black/dark-grey over the light-grey right part (like in the example), same black/dark-grey when the left part is rather light, and white when the left part is rather dark (like the green in the example).
I tried various mix-blend-mode: difference
and color
combinations, couldn't achieve this.
Bare example here
I tried also something along filter: grayscale(1) contrast(9);
.container {
width: 200px;
height: 20px;
position: relative;
background-color: #eee;
text-align: center;
}
.progress {
position: absolute;
top: 0;
left: 0;
width: 50%;
height: 100%;
background-color: #43a047;
}
.text {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
mix-blend-mode: difference;
color: white;
}
<div class="container">
<div class="progress"></div>
<div class="text">Some text here</div>
</div>
Solution 1:
You can create another gradient to color the text without the use of mix-blend mode:
.container {
width: 200px;
height: 20px;
background: linear-gradient(to right, #43a047 50%, #eee 0);
text-align: center;
}
.text {
background: linear-gradient(to right, white 50%, black 0);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
-webkit-text-fill-color: transparent;
font-weight: bold;
}
<div class="container">
<div class="text">Some text here</div>
</div>
And for better flexibility you can use CSS variable to control the progress:
.container {
width: 200px;
height: 20px;
margin:5px;
background: linear-gradient(to right, #43a047 var(--p,50%), #eee 0);
text-align: center;
}
.text {
background: linear-gradient(to right, white var(--p,50%), black 0);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
-webkit-text-fill-color: transparent;
font-weight: bold;
}
<div class="container" style="--p:80%">
<div class="text">Some text here</div>
</div>
<div class="container" style="--p:20%">
<div class="text">Some text here</div>
</div>
<div class="container">
<div class="text">Some text here</div>
</div>