默认定义的颜色如下图所示:
50
,最重是950
,夹在中间的颜色级差都是100
,即不存在yellow-150
这种东西black
和white
:因为纯白和纯黑是没有灰度意义的,所以不在上面这个矩阵表中white
和black
其实有很多样式都会用到颜色,但这里先只提四个最常用的,其它样式碰到了再单独说。
下表中的*
都代表颜色代码,比如white
, black
, yellow-300
, cyan-700
等
样式 | tailwind类语法 | 对应的CSS样式 |
---|---|---|
背景色 | bg-* |
background-color |
前景色,文字色 | text-* |
color |
描边线色 | outline-* |
outline-color |
边框色 | border-* |
border-color |
如下所示:
<div id="colorTestDiv" class="m-10 w-30 h-30 border-10 outline-10 bg-yellow-300 text-rose-700 outline-cyan-600 border-purple-400" onclick="ChangeRandomColor()">
点击这个DIV更换随机颜色
</div>
<script>
colorNames = [
"red",
"orange",
"amber",
"yellow",
"lime",
"green",
"emerald",
"teal",
"cyan",
"sky",
"blue",
"indigo",
"violet",
"purple",
"fuchsia",
"pink",
"rose",
"slate",
"gray",
"zinc",
"neutral",
"stone"
];
colorValues = [
"50", "100", "200", "300", "400", "500", "600", "700", "800", "900", "950"
];
function GetRandomColor() {
const nameIdx = Math.floor(Math.random() * colorNames.length);
const valueIdx = Math.floor(Math.random() * colorValues.length);
return `${colorNames[nameIdx]}-${colorValues[valueIdx]}`;
}
function ChangeRandomColor() {
const colorTestDiv = document.getElementById("colorTestDiv");
oldColorClassNames = [];
colorTestDiv.classList.forEach(className => {
if(className.startsWith("bg-") || className.startsWith("text-") || className.startsWith("outline-") || className.startsWith("border-")) {
if(className === "border-10" || className === "outline-10") {
return;
}
oldColorClassNames.push(className);
}
});
oldColorClassNames.forEach(className => {
colorTestDiv.classList.remove(className);
});
colorTestDiv.classList.add(`bg-${GetRandomColor()}`);
colorTestDiv.classList.add(`text-${GetRandomColor()}`);
colorTestDiv.classList.add(`outline-${GetRandomColor()}`);
colorTestDiv.classList.add(`border-${GetRandomColor()}`);
}
</script>
颜色之外还有个东西叫alpha通道,它代表的是透明度,从0到100,0是完全透明,100是完全不透明。
比如颜色是sky-500
,那么加在颜色上面再叠加透明度信息,就在它屁股后面再加/*
,比如sky-500/73
,这个颜色就是代表在sky-500
的基础上,再添加73%的透明度信息。
如下:
<div class="m-2 p-10 w-30 h-30 bg-yellow-300">
<div id="innerDiv" class="w-10 h-10 bg-rose-600/50"></div>
</div>
<input type="range" id="opacity_input" min="0" max="100" step="1" onchange="ChangeInnerDivOpacity()"/>
<script>
function ChangeInnerDivOpacity() {
const innerDiv = document.getElementById("innerDiv");
const opacityInput = document.getElementById("opacity_input");
const opacityValue = opacityInput.value;
const className = `bg-rose-600/${opacityValue}`;
let classToRemove = "";
innerDiv.classList.forEach(className => {
if(className.startsWith("bg-rose-600/")) {
classToRemove = className;
return;
}
});
innerDiv.classList.remove(classToRemove);
innerDiv.classList.add(className);
}
</script>