为什么使用 css variables
- easier to get started (no transpiling)
- have access to the DOM
1.local scopes
2.change width Js
3.ideal for responsiceness - perfect for themes
什么是 CSS 变量
CSS 变量当前有两种形式:
- 自定义属性。
这些属性使用--where的特殊格式作为名字。例如--example-variable: 20px;即是一个 css 声明语句。意思是将 20px 赋值给--example-varibale 变量。 - 变量。
就是拥有合法标识符和合法的值。可以被使用在任意的地方。可以使用 var()函数使用变量。例如:var(--example-variable)会返回--example-variable 所对应的值
总结:
带有前缀--的属性名,比如--example--name,表示的是带有值的自定义属性,其可以通过 var()函数使用。
补充
- CSS 自定义属性是可以级联的:每一个自定义属性可以多次出现,并且变量的值将会借助级联算法和自定义属性值运算出来。
CSS 变量并不支持 !important 声明,注意只是声明。
- 初始值 *see prose
- 适用元素 *all elements
- 是否是继承属性 *yes
- 适用媒体 *all
- 计算值 *as specified with variables substituted
- Animation type *discrete
- 正规顺序 *per grammar
CSS 变量的继承
html<div class="one"> ?<div class="two"> ???<div class="three"></div> ???<div class="four"></div> ???<div></div> ?</div></div>
css .two { ?--test: 10px;}.three { ?--test: 2em;}
在这个例子中,var(--test)的结果是:
- class="two" 对应的节点: 10px
- class="three" 对应的节点: element: 2em
- class="four" 对应的节点: 10px (inherited from its parent)
- class="one" 对应的节点: 无效值, 即此属性值为未被自定义 css 变量覆盖的默认值
:root
:root 这个 CSS 伪类匹配文档树的根元素。
对于 HTML 来说,:root 表示 元素,除了优先级更高之外,与 html 选择器相同。 所以我们把自定义属性写在:root{}
里面,html 标签里面的元素会继承的。
html<body> ?<section id="container"> ???<div class="item1"></div> ???<div class="item2"></div> ???<div class="item3"></div> ???<div class="item4"></div> ?</section></body>
css #container { ?width: 400px; ?height: 150px; ?background-color: #ffeead; ?border: 1px solid #666; ?display: flex; ?flex-direction: row; ?justify-content: space-around; ?align-items: center;}#container > div { ?width: 70px; ?height: 50px;}#container div:nth-child(2n) { ?background-color: lightgreen;}#container div:nth-child(2n + 1) { ?background-color: lightpink;}
声明变量
css :root { ?--green: lightgreen; ?--lightpink: lightpink;}#container div:nth-child(2n) { ?background-color: var(--green);}#container div:nth-child(2n + 1) { ?background-color: var(--lightpink);}
background-color 的值用 var()代替实现相同的效果
CSS 层级变量
局部变量会在作用范围内覆盖全局变量。
css :root { ?--green: lightgreen; ?--lightpink: lightpink;}#container div:nth-child(2n) { ?background-color: var(--green);}#container div:nth-child(2n + 1) { ?background-color: var(--lightpink);}.item1 { ?--green: black; ?background-color: var(--green) !important; /*选择器权重 ?100+10>10 所以加了!important*/}
使用多个变量
css:root{ ?????--word1:"are"; ?????--word2:"you"; ?????--word3:"ok";}.item2::before { ?????content: var(--word1) " " var(--word2) " " var(--word3);}
完~~
CSS-css
原文地址:https://www.cnblogs.com/guangzan/p/10536053.html