Coming Soon: Native CSS Variables
Name one feature youâd love to see in CSS. Hands up those who want variables⊠(Iâm sure some of you are desperate for parent selectors but youâre in the minority!)
The issue stems from our need to use and repeatedly re-use the same colors and other values throughout a stylesheet. For example:
section { border-color: #334; }
h1 { color: #334; }
p { background-color: #334; }
Maintenance is tougher than it need be. We need to remember a range of hex/RGB values and, inevitably, the finicky client or designer will decide #335 is âon-brandâ. Search and replace might work, but not if youâve used #333344 in some places or rgb(21,21,2c) in others.
CSS variables solve the problem. You define #334 as a single named variable and use it throughout your code. Itâs usually the first feature implemented in CSS pre-compilers. For example, in LESS:
@mycolor: #334;
section { border-color: @mycolor; }
h1 { color: @mycolor; }
p { background-color: @mycolor; }
or Sass
$mycolor: #334;
section { border-color: $mycolor; }
h1 { color: $mycolor; }
p { background-color: $mycolor; }
Fortunately, native CSS variables will arrive soon. Thereâs a draft W3C specification at https://www.w3.org/TR/css-variables/ which reveals how we may be writing CSS code when vendors begin to implement support.
According to the document, any property name starting with the âvar-â prefix is a variable property. For example:
:root
{
var-mycolor: #334;
}
section { border-color: var(mycolor); }
h1 { color: var(mycolor); }
p { background-color: var(mycolor); }
Perhaps thatâs not as concise as LESS/Sass, but itâs a big step forward which will ease the maintenance issues weâve all encountered.
Itâs an exciting development but donât hold your breath. Thereâs no guarantee it will be adopted by all vendors and, even if they do, the feature does not appear to be backward-compatible with older browsers. Our great grand-children will love it, though.