在按钮中定制Bootstrap 5文本颜色对比度

17
我正在使用 bootstrap.build 定制 Bootstrap 5,目前为止没有遇到问题。
图片描述 图片描述

enter image description here

但是,当我切换到react项目时,出现了问题。按钮内的文本变成了黑色。悬停在轮廓按钮上时也是如此。
enter image description here

enter image description here

我所做的就是自定义.scss文件,就像这样:

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

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

出了什么问题?

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

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

那么,Bootstrap 在 React 中和在 bootstrap.build 中有什么区别?背后发生了什么?

这是 codesanbox.io 上的示例项目。请查看并告诉我哪里做错了。
Edit sparkling-paper-5tvvc


它与“颜色对比度”有关。它可以自动检测并决定使用哪种颜色来显示文本。 - Apostolos
1
@Apostolos 正确,我知道。但是,为什么在导入到React时会有所不同?如何解决这个问题?我已经搜索了将近一周的时间。 - Jastria Rahmat
抱歉,我看到您不想使用选择器。我的解决方案基于 button-outline-variant 和选择器。 - Apostolos
您能否在沙盒上添加相同的非 React 项目? - Apostolos
@Apostolos 这是另一个[项目](https://codesandbox.io/s/node-express-pug-bootstrap-sass-jw721?file=/index.js)。结果完全相同。 [这个](https://dev59.com/WVEG5IYBdhLWcg3wUqS6#67958494)答案似乎相关,但我不知道如何在“.scss”文件中实现它。 - Jastria Rahmat
1个回答

42

从检查源代码来看,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 算法


// 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;

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

使用4.x颜色对比逻辑将$primary更改为#e84c22 - 结果是浅色文本颜色

使用5.x颜色对比逻辑将$primary更改为#e84c22 - 结果是暗色文本颜色


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

要在Bootstrap 5 (with 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”。另外,您可以使用我相关答案中描述的5.x解决方案。如果您正在寻找进一步自定义Bootstrap,themestr.app(注:我是创作者)已更新至Bootstrap 5.x。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接