Using mix-blend-mode: Difference
works well when the background color is black to change the text color to white. Move the mouse over the text to see the effect:
const blackBox = document.querySelector(".black-box"); window.addEventLis tener('mousemove', function(event) { blackBox.style.left = `${event.pageX - 50}px`; blackBox.style.top = `${event.pageY - 50}px`; });
.wrapper { background-color: white; } h1 { position: relative; z-index: 2; color: white; mix-blend-mode: difference; } .black-box { width: 100px; height: 100px; position: absolute; z-index: 1; background-color: black; }
<div class="wrapper"> <h1>Lorem Ipsum</h1> </div> <div class="black-box"></div>
This will not produce white text if the background is not black, which is understandable:
const box = document.querySelector(".box"); window.addEventList ener('mousemove', function(event) { box.style.left = `${event.pageX - 50}px`; box.style.top = `${event.pageY - 50}px`; });
.wrapper { background-color: white; } h1 { position: relative; z-index: 2; color: white; mix-blend-mode: difference; } .box { width: 100px; height: 100px; position: absolute; z-index: 1; background-image: url("https://placekitten.com/100/100") }
<div class="wrapper"> <h1>Lorem Ipsum</h1> </div> <div class="box"></div>
Is there any way to change the text color from black to white when the background is different from white?
This is an idea that relies on the background color instead of the
blending mode
. The trick is to use a gradient the same size as the image, moved in the same way to simulate the blend mode: