CSS-非常有用的css变量
為什么使用 css variables#
借用Scrimba上的:
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 變量。
變量。www.zztjfk.com/
就是擁有合法標識符和合法的值??梢员皇褂迷谌我獾牡胤?。可以使用 var()函數使用變量。例如:var(--example-variable)會返回--example-variable 所對應的值
總結:
帶有前綴--的屬性名,比如--example--name,表示的是帶有值的自定義屬性,其可以通過 var()函數使用。
補充
CSS 自定義屬性是可以級聯的:每一個自定義屬性可以多次出現,并且變量的值將會借助級聯算法和自定義屬性值運算出來。www.4000131666.com/
CSS 變量并不支持 !important 聲明,注意只是聲明。
初始值 see prose
適用元素 all elements
是否是繼承屬性 yes
適用媒體 all
計算值 as specified with variables substituted
Animation type discrete
正規順序 *per grammar
CSS 變量的繼承#
Copy
html
<div class="one">
<div class="two">
<div class="three"></div>
<div class="four"></div>
<div></div>
</div>
</div>
Copy
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 標簽里面的元素會繼承的。
Copy
html
<body>
<section id="container">
<div class="item1"></div>
<div class="item2"></div>
<div class="item3"></div>
<div class="item4"></div>
</section>
</body>
Copy
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;
}
聲明變量#
Copy
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 層級變量#
局部變量會在作用范圍內覆蓋全局變量。
Copy
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/
}
使用多個變量#
Copy
css
:root{
--word1:"are";
--word2:"you";
--word3:"ok";
}
.item2::before {
content: var(--word1) " " var(--word2) " " var(--word3);
}
完~~
轉載于:https://blog.51cto.com/14236847/2363868
總結
以上是生活随笔為你收集整理的CSS-非常有用的css变量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 正则表达式基础知识及应用(用于个人学习以
- 下一篇: 逆向研究