使用 CSS 变量反转颜色

Inverting colors with CSS Variables

我想创建一个本地反向主题(现代浏览器)。使用 CSS Vars(CSS 自定义属性)设置颜色阴影。一些元素具有更高的对比度,而另一些元素则具有低对比度。现在倒置的容器有黑色背景。那里的一切都应该被逆转。深灰色应该是浅灰色。浅灰色应该是深灰色。

我的目标是在不重新分配 CSS 选择器中的变量的情况下实现这一目标。对于这个例子来说,这很容易,但实际的代码库很大,而且有很多选择器。所以我只想更改 CSS Vars 而不是那样。此外,我希望保留原始 CSS 变量可编辑。

最终目标模型

显然,简单地重新分配 Vars(亮 = 暗,暗 = 亮)是行不通的。我试图将值转置为新的占位符 var,但这也没有用。 也许我做错了?有没有干净的方法?我不这么认为。

我知道使用 SASS 的解决方法,或使用 mix-blend-mode 的 hack。

游乐场:
https://codepen.io/esher/pen/WzRJBy

示例代码:

<p class="high-contrast">high contrast</p>
<p class="low-contrast">low contrast</p>

<div class="inverted">
  <p class="high-contrast">high contrast</p>
  <p class="low-contrast">low contrast</p>
</div>

<style>
  :root {
    --high-contrast: #222;
    --low-contrast:  #aaa;
  }

  .high-contrast { color: var(--high-contrast) }
  .low-contrast  { color: var(--low-contrast)  }

  .inverted {
    background-color: black;

    /* Switching vars does not work 
    --high-contrast: var(--low-contrast);
    --low-contrast:  var(--high-contrast);
    */

    /* Transposing Vars also doesn't work:
    --transposed-low-contrast: var(--low-contrast);
    --transposed-high-contrast: var(--high-contrast);
    --high-contrast: var(--transposed-low-contrast);
    --low-contrast: var(--transposed-high-contrast);
    */
  }

  /*

  I am aware of this solution (see description above):

  .inverted p.high-contrast { color: var(--low-contrast);   }
  .inverted p.low-contrast  { color:  var(--high-contrast); }

  */
<style>

像这样的事情怎么样:

:root {
  --high-contrast: var(--high);
  --low-contrast: var(--low);
  --high: #222;
  --low: #aaa;
  /* Yes I can put them at the end and it will work, why?
     Because it's not C, C++ or a programming language, it's CSS
     And the order doesn't matter BUT we need to avoid 
     cyclic dependence between variables.
  */
}

.high-contrast {
  color: var(--high-contrast)
}

.low-contrast {
  color: var(--low-contrast)
}

.inverted {
  --high-contrast: var(--low);
  --low-contrast: var(--high);
}
<p class="high-contrast">high contrast</p>
<p class="low-contrast">low contrast</p>

<div class="inverted">
  <p class="high-contrast">high contrast</p>
  <p class="low-contrast">low contrast</p>
</div>