Github上有个叫electron-api-demos的项目,看代码的时候发现了这么一个css文件(variables.css):
:root {
--color: hsl(0,0%,22%);
--color-subtle: hsl(0,0%,44%);
--color-strong: hsl(0,0%,11%);
--color-link: hsl(0,0%,22%);
--color-border: hsl(0,0%,88%);
--color-bg: hsl(0,0%,96%);
--color-accent: black; /* Fallback */
}
/* Category Colors */
.u-category-windows { --color-accent: hsl(116, 30%, 36%); }
.u-category-menu { --color-accent: hsl(194, 60%, 36%); }
.u-category-native-ui { --color-accent: hsl(222, 53%, 50%); }
.u-category-communication { --color-accent: hsl(285, 47%, 46%); }
.u-category-system { --color-accent: hsl(330, 65%, 48%); }
.u-category-media { --color-accent: hsl( 36, 77%, 34%); }
:root在html文档里对应的就是html标签选择器,:root伪类和html标签选择器这两个的区别基本上就是前者的优先级更高一些。但是,那些–color是什么东西?
根据文档https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables,这个叫CSS自定义属性(CSS变量),是具有继承性质的,在:root中定义CSS变量的话,等于是在定义全局变量,在其他具体的选择器(如上述代码中的.u-category-windows)里定义CSS变量等于是在该选择器及其后台选择器这个范围内定义了一个局部变量。下面是这种变量的使用示例:
.about {
--about-space: 4rem;
position: absolute;
display: flex;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
overflow-x: hidden;
overflow-y: auto;
padding: 0;
background-color: hsl(0,0%,98%);
pointer-events: none;
visibility: hidden;
opacity: 0;
transform: scale(1.1);
transition: visibility 0s .12s linear , opacity .12s ease-in, transform .12s ease-in;
}
.about-header {
padding: var(--about-space) 0;
border-bottom: 1px solid hsl(0,0%,88%);
}
说明:.about中定义了一个–about-space局部变量,其值为4rem,在.about-header中通过var(–about-space)来使用前面定义的值4rem,也就是说.about-header的样式等价于:
.about-header {
padding: 4rem 0;
border-bottom: 1px solid hsl(0,0%,88%);
}
写在最后,CSS自定义属性,嗯,IE浏览器是不支持的。