根据 css 中的背景反转文本颜色

invert text color based on background in css

我有一个不同深浅的蓝色网格,它们每个都包含文本,如果背景是深色,我需要文本是白色的,反之亦然,我有:

color: #333;
isolation: isolate;
mix-blend-mode: difference;

但这会以某种方式将元素的背景颜色更改为一些奇怪的橙色灰色。是否有 CSS-only(less-only)选项只会反转文本颜色?

您可以将文本颜色设置为transparent,并使用background-clipfilter将透明文本显示的颜色反转和灰化。

Methods for Contrasting Text Against Backgrounds.

中查看您可以通过这种方式实现的各种效果的更详细说明

就您而言,听起来您正在寻找类似以下的内容:

#one {
  background-color: blue;
}

#two {
  background-color: white;
}

span {
  background: inherit;
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  filter: invert(1) grayscale(1);
  -webkit-filter: invert(1) grayscale(1);
}
<div id="one">
  <span>Some text</span>
</div>
<div id="two">
  <span>Some text</span>
</div>

您还可以将此样式应用到您想要反转颜色的元素:

filter: invert(1);
mix-blend-mode: difference;

如果您需要将差异基于 子元素更远的元素,而不是父元素或接近元素,它尤其有效元素.

我将它与自定义光标(黑色圆圈)一起使用,这使得它与后面的元素形成了很好的对比。样本笔在这里:https://codepen.io/m3t4lch7/pen/VwwOKNd