Vadim Badea Vadim Badea - 3 years ago 343
HTML Question

Reverse Text Color Based on Background

I'm trying to change text color based on the background color. Let's say I have background with black stripes, and the overall background is white, I need the text black on white background and white text on black background.

Is there a way to do it, only with CSS? If no, what are the best practices to do this. See the HTML bellow:

<div class="background">
<p>Aliquam dolor nunc, auctor non dolor vitae, eleifend fringilla felis. Praesent dapibus erat ut nisl commodo ullamcorper.</p>
<p>Morbi eget urna augue. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p>
<p>Nullam laoreet auctor urna at eleifend. Proin venenatis hendrerit mauris, mollis malesuada lorem consectetur et. Aliquam sed iaculis augue.</p>
<p>Donec viverra ex in lectus luctus porttitor.</p>


.background {
width: 480px;
height: 480px;
background-image: url(;
background-size: 480px 480px;

Here's a Codepen for a better understanding. Thanks.

Answer Source

You can achieve this effect using the mix-blend-mode property. I must warn you, support is non-existent in IE. To do what you want to do, you need to have all elements overlap, like you already have, then set the <span> or whatever element you're using for the text to mix-blend-mode: difference;.

If you want to use an actual color, instead of just black and white, another element with that color is required. It needs to cover the entire area you want the color applied to, and have it's mix-blend-mode set to screen.

Here's the catch though, the elements should not be inside each other. The text needs to be above the background elements, but not INSIDE them. I suggest a wrapper <div> to solve this issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download