Is it possible to create a div that dynamically changes text color based on the background color surrounding it? I want the text to switch between two different colors, with the font color being the opposite of the background color. For example, black text on white background and white text on black background. Currently, I am experimenting with "mix-blend-mode" but struggling to set the initial text color before the background change occurs. You can see an example of what I'm trying to achieve in this Codepen. Please check out this image from my mock-up for reference (note that the text appears sideways).
To implement this, you can use the following HTML structure:
<div class="wrapper">
<div class="bg">
<div class="el"></div>
</div>
</div>
And here is a snippet of the CSS styling:
.wrapper {
background-color: rgb(242, 222, 183);
}
$loadingTime: 3s;
$color: rgb(165, 76, 70);
@keyframes loading {
0% {
width: 0%;
} 100% {
width: 100%;
}
}
@keyframes percentage {
@for $i from 1 through 100 {
$percentage: $i + "%";
#{$percentage} {
content: $percentage;
}
}
}
.bg {
background-color: $color;
animation: loading $loadingTime linear infinite;
}
.el{
color: $color;
width: 200px;
border: 1px solid $color;
&:after {
padding-left: 20px;
content: "0%";
display: block;
text-align: center;
font-size: 50px;
padding: 10px 20px;
color: rgb(242, 222, 183);
mix-blend-mode: initial;
animation: percentage $loadingTime linear infinite;
}
}
html {
height: 100%;
background-color: white;
font-family: 'PT Sans', sans-serif;
font-weight: bold;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}