原文連接: Don't miss out on css variablescss
當我第一次據說CSS變量時,我是抱着懷疑態度的。scss、sass、less和stylus這些CSS預處理器不是都有變量機制嗎? 爲何還要使用它?過了幾年,我發現愈來愈多的人開始討論和使用它,我以爲我是錯過了什麼…… 雖然花費了一點功夫,但在使用後,我確實被它吸引住了。這篇文章我會闡述究竟是什麼推進我進一步去探索CSS變量,並在實際項目中使用它。html
譯者注:
本文並不是徹底照搬原文,即意譯. 另外女友也給我校驗過了,確保大致沒有搞錯😂
由於筆者本身原創的文章閱讀量比較慘淡,因此筆者近期會嘗試翻譯一些文章,學習這些文章是怎麼寫的,也積攢點人氣,以便後面原創文章有更多閱讀量sass
在選擇器裏面聲明變量,變量名以--
做爲前綴:less
div {
--bgColor: deeppink;
}
複製代碼
一個流行的方式是在:root
選擇器中定義變量,這至關於定於全局變量:函數
:root {
--bgColor: teal;
}
複製代碼
經過var()
函數來引用變量:學習
div {
background: var(--bgColor);
}
複製代碼
var()
函數還能夠接受一個參數,用做變量的默認值,當變量未定義時回退到這個默認值:ui
header {
background: var(--bgColor);
color: var(--color, beige);
}
複製代碼
上面代碼的運行結果以下:spa
利用CSS變量,能夠很容易地實現主題機制.翻譯
在body元素上爲不一樣的主題建立不一樣的類名,並定義合適的變量值:3d
body.sunrise {
--background-color: #fff;
--text-color: #333;
}
body.sunset {
--background-color: #333;
--text-color: #fff;
}
複製代碼
使用這些變量:
html,
body {
background: var(--background-color);
color: var(--text-color);
}
複製代碼
如今切換body元素的類名到sunrise或sunse,CSS變量會疊層應用到全部選擇器. 效果以下:
我以爲這是CSS變量最好的部分 —— CSS變量能夠經過Javascript API來獲取和設置。SCSS/Less這些預處理器的變量可作不到(部分預處理器已支持編譯到到CSS變量)。
經過getPropertyValue
方法來獲取變量:
getComputedStyle(document.documentElement).getPropertyValue('--color')
複製代碼
若是要獲取具體元素的的變量值, 先經過querySelector
獲取元素:
getComputedStyle(document.querySelector('h1')).getPropertyValue('--color')
複製代碼
經過style.setProperty
來設置變量值:
document.documentElement.style.setProperty('--color', 'red')
複製代碼
設置具體元素的變量值:
document.querySelector('h1').style.setProperty('--color', 'blue')
複製代碼
這個API提供了一個簡潔的方式來使用CSS變量.
幾天前, 我經過David K的XState DEMO接觸到了這個使用場景: 當用戶鼠標拖拽時, 經過CSS變量來肯定選擇框的定位(基於鼠標的開始位置和當前位置):
.selectbox {
left: calc(var(--mouse-x1));
top: calc(var(--mouse-y1));
width: calc((var(--mouse-x2) - var(--mouse-x1)));
height: calc((var(--mouse-y2) - var(--mouse-y1)));
color: rgba(255, 255, 255, 0.5);
background: rgba(0, 0, 0, 0.1);
border: 2px solid currentColor;
position: absolute;
transition: opacity 0.3s ease-in-out;
}
複製代碼
在鼠標事件處理器中更新CSS變量:
document.documentElement.style.setProperty(
'--mouse-x1',
ctx.selectArea.x1 + 'px',
)
document.documentElement.style.setProperty(
'--mouse-y1',
ctx.selectArea.y1 + 'px',
)
document.documentElement.style.setProperty(
'--mouse-x2',
ctx.selectArea.x2 + 'px',
)
document.documentElement.style.setProperty(
'--mouse-y2',
ctx.selectArea.y2 + 'px',
)
複製代碼
若是你像我同樣以爲CSS變量沒有用,或者壓根不知道它的存在,我但願這篇文章能夠爲你開啓一扇門,來探索它的使用場景。
Javascript API讓我踩了很多坑,可是它確實讓我開了眼界,我期待將來可以更多使用和了解它們。