定义新的CSS颜色名称 [英] Define new CSS color name
问题描述
我们知道HTML标准定义了一堆颜色,但是我可以在更少的CSS中定义和使用新颜色吗?
We know the HTML standard defines a bunch of colors, but can I define and use new color in less css?
说我想有一个DoctorWhite颜色,我想像这样使用它
Say I want to have a color DoctorWhite, and I want to use it like
background-color:DoctorWhite;
我知道很少有 css 可以定义变量并将其与 at(@) 符号一起使用.但这看起来不像是本机颜色.
I know less css can define variables and use it with the at(@) notation. But it doesn't look like a native color.
用更少的CSS就能实现吗?还是其他CSS预处理器支持此功能?
Is it achivable in less css? Or does any other CSS pre-processor support this?
推荐答案
:root {
--stackoverflow: #f69c55;
}
.rectangle {
width: 100px;
height: 100px;
margin: 10px auto;
}
.rectangle.default-color {
background-color: black;
}
.rectangle.custom-color {
background-color: var(--stackoverflow);
}
<div class="rectangle default-color">
<!-- will become black -->
</div>
<div class="rectangle custom-color">
<!-- will become orange -->
</div>
在这里, var()
函数用于将 .rectangle.custom-color
的 background-color
属性的值设置为-stackoverflow
变量(即#f69c55
).
Here, the var()
function is used to set the value of the background-color
property of .rectangle.custom-color
to the value of the --stackoverflow
variable (i.e. #f69c55
).
请记住,这是W3C候选建议书(旨在成为W3C规范),因此,正如@Ricky_Ruiz所建议的那样,请确保使用诸如
Bear in mind that this is a W3C Candidate Recommendation (intended to become a W3C spec), so as @Ricky_Ruiz suggested, make sure it is supported by the browsers you are targeting using a service like CanIUse.
旁注:自定义变量名称开头的两个破折号(-
)并非任意:
Side note: The two dashes (--
) at the beginning of the custom variable name are not arbitrary:
自定义属性是名称以两个破折号(U + 002D HYPHEN-MINUS)开头的任何属性,例如
-foo
.产生的内容与此相对应:它的定义是任何以两个破折号开头的有效标识符.
A custom property is any property whose name starts with two dashes (U+002D HYPHEN-MINUS), like
--foo
. The production corresponds to this: it’s defined as any valid identifier that starts with two dashes.
Have a look at section 2 of the Candidate Recommendation document for more.
这篇关于定义新的CSS颜色名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!