【问题标题】:Inverting colors with CSS Variables使用 CSS 变量反转颜色
【发布时间】:2018-08-29 00:39:23
【问题描述】:

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

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

最终目标模型

很明显,对 Vars 的简单重新分配(亮 = 暗,暗 = 亮)不起作用。我试图将这些值转换为一个新的占位符 var,但这也没有奏效。 也许我做错了?有没有干净的方法?我不这么认为。

我知道使用 SASS 的解决方法,或使用混合混合模式的黑客。

游乐场
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>

【问题讨论】:

    标签: html css css-variables


    【解决方案1】:

    这样的事情怎么样:

    :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>

    【讨论】:

    • 谢谢!只需 15 分钟即可解决!我有点感觉到我遗漏了一些东西,很高兴有一个干净的解决方案。
    • @FrankLämmer 欢迎 ;) 顺便说一句,你几乎很好,但你必须考虑 CSS 而不是编程......因为你试图切换两个变量的内容,但 CSS 不是编程语言。 .. 当我们在 CSS 中指定不同的属性时,顺序无关紧要,所以你有某种循环依赖[好吧不容易解释这就是我没有这样做的原因:)] 所以通过添加 2 个新变量,它更容易;)
    猜你喜欢
    • 1970-01-01
    • 2013-07-18
    • 2023-04-09
    • 2017-05-22
    • 2013-06-03
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    相关资源
    最近更新 更多