Ste*_*ler 7 css colors background-color
我们正在改变我们网站的外观。许多元素的颜色都在变化。我们的辅助按钮从带有白色文本的紫色背景变为:

围绕继承背景的红色边框:

我们在许多页面的数百个位置使用此按钮。它驻留在具有各种背景颜色(和一些背景图像)的部分中。
使用旧的按钮处理,我在确定文本颜色时不必担心背景颜色。文本颜色始终为白色:
.secondary-button {
color: white;
}
Run Code Online (Sandbox Code Playgroud)
现在字体颜色将不得不根据背景改变。它需要是白色或紫色,具体取决于背景的暗度。白色在浅色背景上不起作用:

因为这个按钮用在很多地方,我不想手动浏览所有这些按钮并在每个按钮的基础上进行选择。CSS 中有没有办法根据背景的暗度选择两种背景颜色中的一种?就像是:
.secondary-button {
color: calc(background-color>#999?purple:white);
}
Run Code Online (Sandbox Code Playgroud)
我找到了使用 JavaScript 完成此操作的方法:根据覆盖背景区域的亮度更改文本颜色?以及计算颜色有多深的语言不可知算法:根据背景颜色确定字体颜色,但我无法找到纯 CSS 解决方案。
您可以使用 SASS 来实现此目的!
@function set-notification-text-color($color) {
@if (lightness($color) > 50) {
@return #000000; // Lighter backgorund, return dark color
} @else {
@return #ffffff; // Darker background, return light color
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我们使用 Sasslightness()函数来确定哪种颜色更适合背景。)函数lightness(是一个内置的 Sass 函数,它返回 0 到 100 之间的颜色 RGB 值的亮度。其中 0 是最暗的,100 是最亮的。
因此,在我们的函数中,我们接收一种颜色,如果该颜色的亮度值大于 50,这意味着它是浅色,我们将返回一个深色值以确保良好的对比度。否则我们返回浅色。
这是一种替代方法,但您可以使用深色(尽管在某种程度上是半透明的),text-shadow它会在较浅的背景上突出显示按钮的文本,而在较暗的背景上或多或少难以察觉。
例如。text-shadow: 1px 1px rgba(0,0,0,0.5), -1px 1px rgba(0,0,0,0.5), 1px -1px rgba(0,0,0,0.5), -1px -1px rgba(0,0,0,0.5);
例子:
div {
display: inline-block;
width: 280px;
height: 50px;
padding: 45px 5px;
}
div:nth-of-type(1) {
background-color: rgb(70,41,126);
}
div:nth-of-type(2) {
background-color: rgb(235,240,244);
}
.secondary-button {
width: 280px;
height: 50px;
color: white;
font-size: 18px;
font-weight: bold;
text-transform: uppercase;
text-shadow: 1px 1px rgba(0,0,0,0.5), -1px 1px rgba(0,0,0,0.5), 1px -1px rgba(0,0,0,0.5), -1px -1px rgba(0,0,0,0.5);
background-color: transparent;
border: 4px solid rgb(245,69,86);
border-radius: 15px 15px 15px 0;
}Run Code Online (Sandbox Code Playgroud)
<div>
<button type="button" class="secondary-button">Play the Demo</button>
</div>
<div>
<button type="button" class="secondary-button">Play the Demo</button>
</div>Run Code Online (Sandbox Code Playgroud)