# 如果使用深色主题，则使用颜色方案的颜色，否则使用主题中的我的颜色

**URL:** <https://meta.discourse.org/t/use-color-scheme-color-if-dark-scheme-otherwise-use-my-color-in-theme/191365>\
**Category:** Development\
**Created:** [2021年五月23日 10:49 UTC](https://meta.discourse.org/t/use-color-scheme-color-if-dark-scheme-otherwise-use-my-color-in-theme/191365 "2021-05-23T10:49:13Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Alex\_P](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/alex_p/32/163548_2.png) [@Alex\_P](https://meta.discourse.org/u/Alex_P)\
**Post date:** [2021年五月23日 10:49 UTC](https://meta.discourse.org/t/use-color-scheme-color-if-dark-scheme-otherwise-use-my-color-in-theme/191365/1 "2021-05-23T10:49:13Z")

</div>

我想实现类似这样的效果：

```scss
.some-link {
  @if var(--scheme-type) == 'dark' {
    color: var(--primary);
  } @else {
    color: #3b5998;
}

```

但显然这是不可能的，因为 CSS 中没有 `if` 语句，而且 SCSS 也不是在运行时处理的。

据我所知，Discourse 并没有添加任何类来指示当前是否启用了深色模式，而 CSS 也不允许在选择器中使用自定义属性。

有什么好的变通方案吗？

---

<div class="post-metadata">

**Author:** ![awesomerobot](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/awesomerobot/32/142900_2.png) [@awesomerobot](https://meta.discourse.org/u/awesomerobot)\
**Post date:** [2021年五月25日 01:41 UTC](https://meta.discourse.org/t/use-color-scheme-color-if-dark-scheme-otherwise-use-my-color-in-theme/191365/2 "2021-05-25T01:41:53Z")

</div>

我想这就是你在找的：

> [@pmusaraj](#):
>
> 在主题中，你可以通过在 `common/color_definitions.scss` 样式表中声明 CSS 自定义属性来实现同样的效果。你可以参考 [graceful 主题中的这个提交](https://github.com/discourse/graceful/commit/b44f048cd97bf33b8d3316974844476a25466ee0) 作为示例。

因此，在 `color_definitions.scss` 中你可以这样写：

```plaintext
$my-theme-color: dark-light-choose($primary, red);

:root {
  --my-theme-color: #{$my-theme-color};
}

```

然后在你的主题中，你就可以使用这个支持深色/浅色切换的新自定义属性了：

```plaintext
body {
  color: var(--my-theme-color);
}

```

---

<div class="post-metadata">

**Author:** ![Alex\_P](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/alex_p/32/163548_2.png) [@Alex\_P](https://meta.discourse.org/u/Alex_P)\
**Post date:** [2021年五月25日 05:21 UTC](https://meta.discourse.org/t/use-color-scheme-color-if-dark-scheme-otherwise-use-my-color-in-theme/191365/3 "2021-05-25T05:21:47Z")

</div>

太好了，看起来能用了 😋

参数顺序和函数名不太一致，有点奇怪。

> <https://github.com/discourse/discourse/blob/50926f614342336793f1b78672b387d545d48de3/app/assets/stylesheets/common/foundation/variables.scss#L206>

所以应该是 `dark-light-choose(#3b5998, $primary)`。
