Text Color Based on Background Color

996 views Asked by At

I want to make a div that has text that will change color based on the background color around it. The color in the div will change between 2 different colors and I want the text color to be the opposite of those colors. So the text is black when the background is white and text is white when the background is black. I am currently using "mix-blend-mode" but I can't get the initial text color to be the opposite of the background color before the background color change. Here is a Codepen of what I mean when I say the color will change. It won't be a loading bar type of change like that but you get the idea. Also here is an image from my mock-up. It is sideways because the text will be sideways on the page.

HTML:

<div class="wrapper">
  <div class="bg">
    <div class="el"></div>
  </div>
</div> 

CSS:

.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%;
} 
1

There are 1 answers

0
Arsham On

I have found a solution which lets your text be inversed depending on the background color it is an easy tutorial to follow I think.

it uses properties like mix-blend-mode: difference;

Link to solution

I hope it helps you in your coding adventure