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瀏覽器是不支持的。