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>
</div>
CSS
.background {
width: 480px;
height: 480px;
background-image: url(http://www.musicsquare-pro.com/construction/wp-content/themes/punch/images/masks/mask_square_dark.png);
background-size: 480px 480px;
}
Here's a Codepen for a better understanding. Thanks.
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.
You can put this:
for the background: background-color: black;
or background-color: white;
for the text: color: black;
or color:white;
.
上一篇: 更改背景的颜色
下一篇: 基于背景的反向文本颜色