Coming Soon: Native CSS Variables

Share this article

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.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

CSSCSS3HTML5 Dev Centervariables
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form