【问题标题】:Customize bootstrap 5 text color contrast in button在按钮中自定义 bootstrap 5 文本颜色对比度
【发布时间】:2021-09-18 17:28:25
【问题描述】:

我正在使用 bootstrap.build 自定义引导程序 5。到目前为止,我没有任何问题。

但是,当我切换到 react 项目时,事情就出错了。按钮内的文本变为黑色。悬停时,大纲按钮也是如此。

我所做的只是自定义.scss 文件,如下所示:

$orange: #e84c22;
$primary: $orange;

@import "~bootstrap/scss/bootstrap.scss";

怎么了?

我的目标是使用 #e84c22 的确切颜色更改这些按钮,以仅使用 btn btn-outline-primarybtn btn-primary 类显示白色文本。

我尝试将$yiq-contrasted-threshold 更改为200,但没有任何改变。

那么,Bootstrap in react 和 bootstrap.build 有什么区别呢?背后发生了什么?

这里是 codesanbox.io 中的示例项目。请检查并告诉我我做错了什么。

【问题讨论】:

  • 它与color-contrast有关。它会自动检测并决定文本使用哪种颜色
  • @Apostolos 正确,我知道这一点。但是,为什么当我导入它来做出反应时它会有所不同?以及如何解决这个问题?我一直在寻找这个东西差不多一个星期了。
  • 对不起,我看到你不想使用选择器。我的解决方案基于button-outline-variant 和选择器
  • 你能在沙盒上添加相同的非反应项目吗?
  • @Apostolos 这是另一个project。结果是一样的。 this 答案似乎相关,但我只是不知道如何在 .scss 文件中实现它。

标签: css reactjs twitter-bootstrap sass bootstrap-5


【解决方案1】:

从查源来看,bootstrap.build/app 使用的是 Bootstrap 4,不是 Bootstrap 5。颜色对比逻辑从 Bootstrap 4 变成了 Bootstrap 5,颜色对比阈值很不一样。

Bootstrap 4 使用了 YIQ 颜色空间...

// The yiq lightness value that determines when the lightness of color changes from "dark" to "light". Acceptable values are between 0 and 255.
$yiq-contrasted-threshold:  150 !default;

Bootstrap 5 使用 WCAG 2.0 algorithm

// The contrast ratio to reach against white, to determine if color changes from "light" to "dark". Acceptable values for WCAG 2.0 are 3, 4.5 and 7.
// See https://www.w3.org/TR/WCAG20/#visual-audio-contrast-contrast
$min-contrast-ratio:   4.5 !default;

比较两个版本,颜色逻辑:

Using the 4.x color contrast logic to change $primary to #e84c22 - 产生浅色文本颜色

Using the 5.x color contrast logic to change $primary to #e84c22 - 导致深色文本颜色


因此,您的 Bootstrap 5 React SASS 自定义项按预期工作,并且 bootstrap.build 仍在使用较旧的 4.x。

要在 Bootstrap 5(使用 React)中获得浅色文本颜色,您可以更改 $min-contrast-ratio 变量的默认值...

例如,将 $min-contrast-ratio 从 4.5 更改为 3 会使文本颜色与 #e84c22 形成鲜明对比:

$min-contrast-ratio: 3;
$orange: #e84c22;
$primary: $orange;

@import "~bootstrap/scss/bootstrap.scss";

https://codeply.com/p/Z1tOoBclnH

如 Bootstrap 5 SASS 中所述,“WCAG 2.0 的可接受值为 3、4.5 和 7”。或者,您可以使用我的related answer 中描述的 5.x 解决方案。如果您希望进一步自定义 Bootstrap,themestr.app(注意:我是创建者)已更新为 Bootstrap 5.x。

【讨论】:

  • 哇!,来自创作者的直接回答。 :D 我以前访问过你的网站,但它是 bootstrap 4。现在它是 v5。现在一切正常,你是最棒的。
猜你喜欢
  • 2021-08-29
  • 2015-10-18
  • 2014-11-17
  • 2018-10-17
  • 2020-08-13
  • 2021-08-05
  • 1970-01-01
  • 2021-04-13
相关资源
最近更新 更多