如果你像我一样,你对CSS变量的游戏有点晚。也许你(像我一样)一直在享受使用CSS-in-JS的真正JavaScript变量。但该死的是,我所认识和尊重的聪明人都说它很了不起,我应该接受这个相对较新的平台。
当我开始接触一些东西的时候,我真的很喜欢得到一个超级简单的开始,所以给你。
我在谈话中听到了 "CSS变量 "和 "CSS自定义属性 "的说法,但我并不真正理解它们的区别。结果发现它们是一回事🤦♂️技术术语是 "CSS自定义属性",但它通常被称为 "CSS变量"。
好了,给你。你的自定义属性的快速入门:
<html>
<style>
:root {
--color: blue;
}
.my-text {
color: var(--color);
}
</style>
<body>
<div class="my-text">This will be blue</div>
</body>
</html>
:root 是一个伪类,与.NET的属性相匹配。实际上,它和我们用 来代替 完全一样(除了它的特异性更高)。html :root
就像CSS中的其他东西一样,你可以将你的自定义属性范围扩大到文档的各个部分。因此,我们可以使用普通的选择器,而不是:root 。
<html>
<style>
.blue-text {
--color: blue;
}
.red-text {
--color: red;
}
.my-text {
color: var(--color);
}
</style>
<body>
<div class="blue-text">
<div class="my-text">This will be blue</div>
</div>
<div class="red-text">
<div class="my-text">This will be red</div>
</div>
</body>
</html>
级联也适用于此。
<html>
<style>
.blue-text {
--color: blue;
}
.red-text {
--color: red;
}
.my-text {
color: var(--color);
}
</style>
<body>
<div class="blue-text">
<div class="my-text">This will be blue</div>
<div class="red-text">
<div class="my-text">
This will be red (even though it's within the blue-text div, the
red-text is more specific).
</div>
</div>
</div>
</body>
</html>
而且你甚至可以用JavaScript来改变自定义属性的值。
<html>
<style>
.blue-text {
--color: blue;
}
.red-text {
--color: red;
}
.my-text {
color: var(--color);
}
</style>
<body>
<div class="blue-text">
<div class="my-text">
This will be green (because the JS will change the color property)
</div>
<div class="red-text">
<div class="my-text">
This will be red (even though it's within the blue-text div, the
red-text is more specific).
</div>
</div>
</div>
<script>
const blueTextDiv = document.querySelector('.blue-text')
blueTextDiv.style.setProperty('--color', 'green')
</script>
</body>
</html>
就这样,这就是你的超级简单的开始。我并没有真正谈论你为什么要这样做。我将让你继续在谷歌上搜索来弄清楚(或者让你的想象力尽情发挥)。希望这能帮助你快速了解这个想法!祝您好运。