css 预处理器(Sass/Less/Stylus)支持一个最基本的功能,就是在 css 里面可以定义变量,书写大量重复的颜色时就不用重新写了,大大提高提升开发效果和代码的可读性。如果现在我告诉你 css 也支持了,你是不是打断腿也不信(兼容性忽略 IE,放心使用)。
css 变量的基本语法
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
:root{
--蓝色: blue;
}
h1{
color: var(--蓝色);
}
</style>
</head>
<body>
<h1>标题</h1>
</body>
</html>
变量定义和使用方式
CSS 中原生的变量定义语法是:--x:**;
,变量使用语法是:var(--x)
,其中 x 表示我们的变量名称。**
表示定义的属性值。至于 x 变量命名规范,只要不包括 $,[,^,(,%
等字符,可以是 数字[0-9] 字母[a-zA-Z] 下划线_ 和 短横线 - 这些组合,甚至可以是中文,日文或者韩文
。
变量的作用范围
先来看看变量应该定义在哪里才能起作用?
--深蓝: #369;
body {
background-color: var(--深蓝);
}
变量的使用范围和权重看下面这个案例:
<!DOCTYPE html>
<html>
<head>
<style>
:root { --color: blue; }
div { --color: green; }
#alert { --color: red; }
* { color: var(--color); }
</style>
</head>
<body>
<p>猜我的颜色是什么?blue(蓝色继承与根元素)</p>
<div>猜我的颜色是什么?green(绿色直接设置)</div>
<div id="alert">猜我的颜色是什么?red()</div>
</body>
</html>
上面实验结果说明:
- 变量也是跟着CSS选择器走的,如果变量所在的选择器和使用变量的元素没有交集,是没有效果的。例如#alert定义的变量,只有 id 为 alert 的元素才能享有。特殊的如果你想变量全局使用,则你可以设置在
:root
选择器上; - 下面就是权重的规则,变量的覆盖规则由 CSS 选择器的权重决定的,但并无 !important 这种用法。
css 预处理器属性名可以为变量,我们这个支持吗?试一下:
:root{
--blue: blue;
}
html{
--bg: background-color;
var(--bg): var(--blue);
}
实验结果页面并没变蓝,很遗憾不支持。
CSS变量使用完整语法:var(变量名,默认值)
默认值可省略。
:root{
/*--blue: blue;*/
}
html{
background-color: var(--blue,red);
}
CSS变量的值不合法时:
<!DOCTYPE html>
<html>
<head>
<style>
:root{
--蓝色: 90px;
}
h1{
color: var(--蓝色,red);
}
</style>
</head>
<body>
<h1>我是标题</h1>
</body>
</html>
猜猜 h1 标签的文字有什么变化?没变化。css 遇见不合法的东西会正常的声明解析,但因为它不合法,所以值为默认值。
CSS变量的空格尾随特性
<!DOCTYPE html>
<html>
<head>
<style>
:root{
--fontsize: 90;
}
h1{
font-size: var(--fontsize)px;
}
</style>
</head>
<body>
<h1>我是标题</h1>
</body>
</html>
猜猜 h1 标签里面的文字大小是多少?
但是可以使用 CSS3 calc() 计算来实现:
:root{
--fontsize: 90;
}
h1{
font-size: calc(var(--fontsize) * 1px);
}
此时,h1 标签内的字体才是 90px。
JS 操作 CSS 变量
让变量生效:
<!DOCTYPE html>
<html>
<head>
<style>
h1{
color: var(--blue);
}
</style>
</head>
<body>
<h1 id = "title">我是标题</h1>
<button onclick = "down()">按我生效</button>
<script>
let h1 = document.getElementById("title");
function down(){
h1.style.setProperty("--blue","blue");
}
</script>
</body>
</html>
如何读到 css 变量的值:
<!DOCTYPE html>
<html>
<head>
<style>
h1{
color: var(--blue);
}
</style>
</head>
<body>
<h1 id = "title">我是标题</h1>
<button onclick = "down()">按我生效</button>
<button onclick = "get()">按我获取h1标签变量的值</button>
<p>获取的颜色值为:</p>
<script>
let h1 = document.getElementById("title");
function down(){
h1.style.setProperty("--blue","blue");
}
function get(){
document.body.innerHTML += getComputedStyle(h1).getPropertyValue("--blue");
}
</script>
</body>
</html>
获取设置的 h1 标签的变量值并展示如下:
补充两个链接:
- 一个使用媒体布局结合css变量实现的响应式布局
- 兼容 IE 浏览器:css-vars-ponyfill
最后
估计很多人使用使用 css 预处理器最常用的就两个东西,一个是定义变量,另一个是可嵌套使用。现在原生 css 实现了变量,接来下要是能实现 css 原生支持嵌套。css 预处理器估计就废了,将会算是一场小小的革命吧。