CSS原生变量(CSS自定义属性)
示例地址:https://github.com/ccyinghua/Css-Variables
一、css原生变量的基础用法
变量声明使用两根连词线"--"表示变量,"$color"是属于Sass的语法,"@color"是属于Less的语法,为避免冲突css原生变量使用"--"
// 声明变量 --color:#000; // 读取变量 var(--color)
注:
1、变量声明不能包含$,[,^,(,%等字符,普通字符局限在只要是“数字[0-9]”“字母[a-zA-Z]”“下划线_”和“短横线-”这些组合,但是可以是中文,日文或者韩文
2、变量的值可以是颜色、字符串、多个值的组合等
示例:
<h3>css variables基础使用</h3> <div class="btn_box"> <button type="button" class="login_btn">登录</button> </div>
/* css variables基础使用 */ :root{ --content1:"abc"; --content2:"efg"; --width:calc(100px + 200px); --btn-bg:#279cff; --字体:18px; } .btn_box:before{ content:var(--content1)' with add'; display:block; line-height: 50px; } .btn_box:after{ content:var(--content1)','var(--content2); display:block; line-height: 50px; } .login_btn{ width:var(--width); height:50px; border-radius:30px; border:0; background: var(--btn-bg); box-shadow: 0 5px 5px rgba(39,156,255,.42); text-align: center; font-size:var(--字体); line-height: 50px; color:#fff; cursor:pointer; outline:none; }
二、作用域
1、变量是遵循CSS语法的优先级高低的 Id > class > 标签 > *
2、注意并无!important这种用法;
3、如果变量所在的选择器和使用变量的元素没有交集,是没有效果的。
<div>蓝色</div> <div class="divbox">绿色</div> <div class="divbox" id="alert">红色</div>
:root { --color: blue; } .divbox { --color: green; } #alert { --color: red; } div{ color: var(--color); width:300px; line-height: 50px; text-align: center; }
三、响应式
div { --color: #7F583F; --bg: #F7EFD2; } .mediabox { color: var(--color); background: var(--bg); } @media screen and (min-width: 768px) { body { --color: #F7EFD2; --bg: #7F583F; } }
四、注意事项
1、属性名(例:width/height/margin....等)不可以走变量
.divbox { --side: margin-top; /* 无效 */ var(--side): 20px; }
2、var()的完整的写法是"var(<自定义属性名> [, <默认值 ]?)",在变量的名字后面可以有一个默认值,如果引用的变量没有定义(注意,仅限于没有定义),则使用后面的值作为元素的属性值
body { background:var(--bg,skyblue); }
3、如果变量值是不合法的,例如下面设置背景色background只能是色值而不能是像素,则使用背景色属性的默认值代替。
body { --bg: 20px; background-color: #369; background-color: var(--bg, #cd0000); }
等同于
body { --bg: 20px; background-color: #369; background-color: transparent; }
4、CSS变量设置数值
(1)
h3 { --size: 30; font-size: var(--size)px; }
结果h3元素的字体大小就是本身的默认大小
(2)
h3 { --size: 30px; font-size: var(--size); } 等于 h3 { font-size:30px; }
(3)使用CSS3 calc()计算:
h3 { --size: 30; font-size: calc(var(--size) * 1px); } 等于 h3 { font-size:30px; }
5、如果变量值带有单位,就不能写成字符串。
/* 无效 */ .divbox { --size: '30px'; font-size: var(--size); } /* 有效 */ .divbox { --size: 30px; font-size: var(--size); }
6、进行calc()运算时,最好能提供默认值: calc(var(--base-line-height, 0) * 1rem)
7、不能作为媒体查询值使用:
@media screen and (min-width: var(--desktop-breakpoint) {})
8、图片地址,如url(var(--image-url)) ,不会生效
五、兼容性处理
检测浏览器是否支持CSS自定义属性的方法。
/*css*/ @supports ( (--a: 0)) { /* supported */ } @supports ( not (--a: 0)) { /* not supported */ }
// Js if (window.CSS && window.