WebKit Experiments with CSS Variables

WebKit, the code that makes up the guts of browsers such as Apple’s Safari, has gained a much-requested new feature with the addition of variables in cascading stylesheets.

The feature, which won’t be available publicly until the next major release of Safari — and then only if it survives this experiment — is available now with its latest nightly WebKit build.

The enhancement comes after ten years of pleas for the feature by web developers. It would make designing and reading website code much easier by allowing developers to reference commonly-used styles by names chosen by the site’s designer. For example, watch how variables make this little piece of code, used to make the background of the page and tables light gray, a little more readable:

Without variables:


//Sets the background of the page and tables to the hex code for the color gray.

body {

   background-color:#ECEAE1;}

table {

   background-color: #ECEAE1;}

With CSS variables:


//Defines "DefaultBGColor" to light gray

@variables {

  DefaultBGColor: #ECEAE1;}

//Sets the background and any table on the page to the default background color

body {

  background-color: var(DefaultBGColor);}

table {

  background-color: var(DefaultBGColor);}

Current implementations of CSS have some standard variables for properties like alignment or color (“left,” “dark blue” or “red,” for example). However, unless you design your site around those pre-defined colors, you’re stuck having to memorize hex codes and pixel lengths. This is especially challenging for sites with multiple designers referencing the same code. Variables would mirror other coding standards by making these references configurable and recognizable according to site design.

Webkit, the rendering engine that powers Apple’s Safari and Linux’s Konqueror, is the first browser to support CSS variables. Web designers are not likely to take advantage of it until other major browsers, like Microsoft’s Internet Explorer and Mozilla’s Firefox, hop on the bandwagon. Still, it’s a nifty advancement, and something worth noting for the future.

To get started with Cascading Style Sheets (CSS), follow Webmonkey’s tutorial.