CSS3为我们提供了一个强大的功能自定义属性,也就是变量,他能让我们更改色系、皮肤、自适配变得简单。
查看兼容性
https://caniuse.com/?search=--
可以看出94%的用户的浏览器都兼容这个新特性了。
变量的定义使用--name
,而变量的调用使用var(--name)
。
示例
/* 定义全局变量 */
:root{
--navColor: #c00;
--navPadding: 10px;
}
/* 定义局部变量 */
.mdiv{
--boxBorder: 2px solid rgba(0, 0, 0, .2);
}
/* 使用var函数定义变量 */
.mdiv{
--borderWidth: 8px;
--borderColor: red;
--borderStyle: solid;
--border: var(--borderWidth) var(--borderColor) var(--borderStyle);
border: var(--border);
}
其中
:root
定义的是全局的变量。
项目示例:
效果
代码:
:root{
--blue: #007bff;
--indigo: #6610f2;
--purple: #6f42c1;
--pink: #e83e8c;
--red: #dc3545;
--orange: #fd7e14;
--yellow: #ffc107;
--green: #28a745;
--teal: #20c997;
--cyan: #17a2b8;
--white: #fff;
--gray: #6c757d;
--gray-dark: #343a40;
--primary: #007bff;
--secondary: #6c757d;
--success: #28a745;
--info: #17a2b8;
--warning: #ffc107;
--danger: #dc3545;
--light: #f8f9fa;
--dark: #343a40;
--breakpoint-xs: 0;
--breakpoint-sm: 576px;
--breakpoint-md: 768px;
--breakpoint-lg: 992px;
--breakpoint-xl: 1200px;
--breakpoint-sl: 1600px;
}
作用域
在全局和布局同时定义了一个变量,会优先应用局部作用域。
优先级
CSS获取变量和CSS的样式优先级一样
顺序是:
!important
>style=""
>#id
>.class
>tagName
>:root
;
// 获取行内样式的变量名
element.style.getPropertyValue("--variableName");
// 获取样式表里定义的变量
getComputedStyle(element).getPropertyValue("--variableName");
// 设置变量的值
element.style.setProperty("--variableName", value);
CSS检测:
通过@supports性能查询语法来检测
语法:
@supports (--a: 0){
.box{
background-color:#c00;
}
}
@supports(not(--a: 0)){
.box{
background-color:#cc0;
}
}
JS语法检测:
const isSupported = window.CSS && window.CSS.supports && window.CSS.supports('--a', 0);
if (isSupported) {
/* supported */
} else {
/* not supported */
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有