Home > Software engineering >  How to make text a different color on overlap in HTML/CSS/JS
How to make text a different color on overlap in HTML/CSS/JS

Time:06-06

I'd like to make some animations with text and for the colours I'd like for the text colour to change depending on the background (the objects it overlaps). However, the effect I'm after doesn't work simply with opacity as I would like a different colour altogether.

For instance: enter image description here

Note that I made this example using GIMP. Also note that the text wouldn't be always aligned/overlapping like this but only during an animation.

Is this effect relatively easy to do or would it require complex JavaScript code and libraries?

CodePudding user response:

You can read more about CSS animation on w3school web :

https://www.w3schools.com/css/css3_animations.asp

CodePudding user response:

Here's an example of the sort of thing that can be done using mix-blend-mode.

This snippet just uses difference - you will have to try out different methods depending on the color combinations you want.

Using difference on the two bits of text and putting them on a white background and making the texts yellow to start with converts them to a sort of blue and then when the animated text hits the blueish background we get a lighter shade.

I'm afraid I've never found a simple, algorithmic way of deciding what values should be given to mix-blend-mode and always end up with experimenting.

.container {
  width: 100vw;
  height: 10em;
  background-image: linear-gradient(-45deg, #5920d6 0 40%, transparent 40% 100%);
  background-color: white;
  overflow: hidden;
  position: relative;
  display: inline-block;
}

.container>* {
  color: #5920d6;
  color: yellow;
  font-family: sans-serif;
  font-size: 3em;
  mix-blend-mode: difference;
}

.static {
  position: absolute;
  top: 40%;
  display: inline-block;
  color: yellow;
}

.move {
  position: absolute;
  animation: move 10s linear infinite;
  top: calc(40%   0.25em);
  color: yellow;
}

@keyframes move {
  0% {
    transform: translate(0, -0.1em);
  }
  100% {
    transform: translate(50vw, -0.1em);
  }
}
<div >
  <div >Some text</div>
  <div >Hello World</div>
</div>

  • Related