span[style*="--length"]
{
width:calc(var(--length, 1)*var(--char-width, 7.23438)*1px);
display:inline-block
}
1.css中的“[]”
span[style*="--length"]
匹配所有style包含了"–length"字符串的span元素,所有用法如下:
span[class='test'] =>匹配所有带有class类名test的span标签
span[class *='test'] =>匹配所有包含了test字符串的class类名的span标签
span[class] =>匹配所有带有class属性的span标签
[class='all'] =>匹配页面上所有带有class='all'的标签
[class *='as'] =>匹配页面上所有class类且类名带有as字符串的类的标签
2.css中的calc函数
calc()函数用一个表达式作为它的参数,用这个表达式的结果作为值。这个表达式可以是任何如下操作符的组合,采用标准操作符处理法则的简单表达式。
- +加法
- -减法
- *乘法,乘数中至少要有一个是 <number> 类型的
- /除法,除数(/右面的数)必须是 <number> 类型的
3.css中的变量
申明变量
:root {
--green: lightgreen;
--lightpink: lightpink;
}
使用变量
#container div:nth-child(2n) {
background-color: var(--green);
}
4.var() 函数
var()函数用于读取变量。
var()函数还可以使用第二个参数,表示变量的默认值。如果该变量不存在,就会使用这个默认值。
#container div:nth-child(2n) {
background-color: var(--green, lightgreen);
}
5.js对css变量的操作写法
// 设置变量
document.body.style.setProperty('--primary', '#7F583F');
// 读取变量
document.body.style.getPropertyValue('--primary').trim();
// '#7F583F'
// 删除变量
document.body.style.removeProperty('--primary');
6.兼容性处理
对于不支持 CSS 变量的浏览器,可以采用下面的写法:
a {
color: #7F583F;
color: var(--primary);
}
也可以使用@support命令进行检测:
@supports ( (--a: 0)) {
/* supported */
}
@supports ( not (--a: 0)) {
/* not supported */
}
JavaScript 也可以检测浏览器是否支持 CSS 变量:
const isSupported =
window.CSS &&
window.CSS.supports &&
window.CSS.supports('--a', 0);
if (isSupported) {
/* supported */
} else {
/* not supported */
}
另外,可以了解sass和less编写的css。
参考链接(比较全面):
http://www.ruanyifeng.com/blog/2017/05/css-variables.html