【问题标题】:Text Color Based on Background Color基于背景颜色的文本颜色
【发布时间】:2023-11-26 08:49:01
【问题描述】:

我想创建一个 div,它的文本会根据周围的背景颜色改变颜色。 div 中的颜色将在 2 种不同颜色之间变化,我希望文本颜色与这些颜色相反。因此,当背景为白色时,文本为黑色,当背景为黑色时,文本为白色。我目前正在使用“混合混合模式”,但在背景颜色更改之前,我无法让初始文本颜色与背景颜色相反。这是Codepen,当我说颜色会改变时,我的意思是。它不会是像这样的加载条类型的变化,但你明白了。这里还有一个来自我的模型的image。它是横向的,因为文本将在页面上横向。

HTML:

<div class="wrapper">
  <div class="bg">
    <div class="el"></div>
  </div>
</div> 

CSS:

.wrapper {
  background-color: rgb(242, 222, 183);
}

$loadingTime: 3s;
$color: rgb(165, 76, 70);

@keyframes loading {
  0% {
    width: 0%;
  } 100% {
    width: 100%;
  }
}

@keyframes percentage { 
  @for $i from 1 through 100 {
    $percentage: $i + "%";
    #{$percentage} {
      content: $percentage;
    }
  }
}

.bg {
  background-color: $color;
  animation: loading $loadingTime linear infinite;
}

.el{
  color: $color;
  width: 200px;
  border: 1px solid $color;

  &:after {
    padding-left: 20px;
    content: "0%";
    display: block;
    text-align: center;
    font-size: 50px;
    padding: 10px 20px;
    color: rgb(242, 222, 183);
    mix-blend-mode: initial;
    animation: percentage $loadingTime linear infinite;
  }
}

html {
  height: 100%;
  background-color: white;
  font-family: 'PT Sans', sans-serif;
  font-weight: bold;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
} 

【问题讨论】:

  • 这只会让一切都淡入到 100%;我希望数字是纯红色,直到红色覆盖,然后我希望它切换到棕褐色。 Here 它有不同的颜色并使用“mix-blend-mode: difference;”
  • 当然!它不一定是 CSS 但请记住,文本上的颜色将主要由于屏幕大小而改变。它将在整个页面上分割对角线颜色。
  • 我很感激!

标签: html css colors mix-blend-mode


【解决方案1】:

我找到了一个解决方案,它可以让您的文本根据背景颜色反转,我认为这是一个简单的教程。

它使用像mix-blend-mode: difference;这样的属性

Link to solution

希望它对您的编程之旅有所帮助

【讨论】: