Custom properties
Preprocessors such as SASS are used to store variables which are used throughout a project, however thet have some limitations which custom properties solve...
- You cannot change them dynamically
- They are not aware of the DOM’s structure
- They cannot be read or changed from JavaScript
Usage
:root {
--main-color: red;
}
.box {
--box-color: #141414;
--box-padding: 10px;
background: var(--box-color, --main-color);
padding: var(--box-padding, fallback);
top: calc(var(--box-padding) + 20px);
}
.box.active {
--box-color: pink;
}
Using with pseudo elements
<div class="box" style="--box-name: 'Shane';">
.box:after{
content: var(--box-name);
}
Scope
Shares similarities to JS with local and global scopes
global
<div class="enclosing">
enclosing
<div class="closure">
closure
</div>
</div>
:root {
--globalVar: 10px;
}
.enclosing {
--enclosingVar: 20px;
font-size: var(--closureVar);
/* NOT ACCESSIBLE */
}
.enclosing .closure {
--closureVar: 30px;
font-size: calc(var(--closureVar) + var(--enclosingVar) + var(--globalVar));
/* 60px */
}
Accessing with JS
See the Pen CSS Custom properties by Shane Prendergast (@webknit) on CodePen.
Refs
It's time to start using CSS Custom properties - Smashing mag