CSS Variables

It is very common to find repeated property values in a CSS stylesheet. CSS Variables allow authors to define variables that are reusable as property values anywhere in a stylesheet and queryable/modifiable through an extension of the CSS Object Model.

CSS Variables can define stylesheet-wide values identified by a token and usable in all CSS declarations. A recurring value, like colors or background-color in a stylesheet, will be way easier to update across the stylesheet if a developer has to modify at just one single place or value instead of modifying all style rules applying the property:value pair.

CSS Variables, once implemented, will allow authors to define variables that are reusable as property values anywhere in a stylesheet and queryable/modifiable through an extension of the CSS Object Model.

Majority of the Web Designers and Developers has been requesting a way of defining CSS Variables since its early release. Nonetheless, some are of the opinion that it is not needed and will complicate matters.

Why variables in CSS?

Many a times, any CSS developer would have felt that s/he is using repeated property values in a CSS stylesheet, for instance to make sure semantically different elements in a web page have a similar rendering and user experience. CSS does offer a way to group styles using groups of selectors, but we tend to neglect it more because of the fact that it’s difficult to maintain, decreases readability and of course semantically distinct elements rarely share all style rules.

CSS Variables Note names David Hyatt of Apple as one of the author, the other is Daniel Glazman of Disruptive Innovations. We might see a early implementation of CSS Variables in a future version of Safari!

The CSS Variables Definition

CSS Variables should be defined in an @variables at-rule. An @variable at-rule is composed of the ‘@’ character followed by the ‘variables’ identifier, optional target media types (separated by commas) and a block of variable definitions. The definition of a variable must precede all style rules contained or imported in the stylesheet.

Each variable definition contained in the block of variables is a declaration composed as CSS style declarations of an identifier, a semi-colon and one value. As in CSS declarations, optional whitespaces and comments are allowed anywhere.

The definition of variables crosses @import boundaries. That means that the definition of a variable contained in a Stylesheet B imported from a Stylesheet A applies to all rules directly contained or imported into Stylesheet A.

Usage Example

Using the value of a variable as the value or one of the values of a property in a CSS declaration should be achieved using the new functional notation var(). This function takes only one argument being the identifier being the name of the variable. The declaration becomes invalid if the variable does not exist.

@variables {
	oColor: #fefedb;
	oBgColor: #ccc;
	oMargin: 1em;
	oPadding: 1em;
}
@variables print { /* applies only to print */
	oColor: #000;
	oBgColor: #fff;
	oMargin: 2em;
	oPdding: 2em;
}
div#post div.entry {
	border: 1px solid #666;
	font: normal normal normal 1em/1.6em "Lucida Grande", Lucida, Verdana, sans-serif;
	margin: var(oMargin);
	padding: var(oPadding);
	color: var(oColor);
	background-color: var(oBgColor);
}

The above shows that we’ve styled the div#post div.entry with color, background-color, padding and margin which have been defined earlier in @variables for screen medium by default and we can override the same same for “print” medium through the @variables print.

More advanced details of CSS Variables — Grammar, Interfaces like CSSRule, CSSVariablesRule, CSSVariablesDeclaration, CSSValue, CSSVariable, etc — are discussed in details at the CSS Variables Note.

Ok, so what if I want to start using CSS Variables now?

There are many hacked solutions available at the moment, though restricted to PHP environment, to inject variables inside your CSS. Some of them like CSS-PHP Variable and Variables in your CSS via PHP treats CSS like PHP and thus able to inject PHP variables rendering them inside your CSS codes.

The near perfect way in the line of the above CSS Variables initiative is luckily available at Shaun Inman’s website — CSS Server-side Constants.

CSS-SSC

CSS-SSV hijacks the syntax of @rules to isolate variable definitions. Variable names and their values are defined like any other CSS property. The goal was to make this as easy-to-use and native-looking as possible:

@server variables {
	variableName: variableValue;
}

This is how variables are embeded in the CSS:

selector {
	property: variableName;
}

Here is an example from Shaun’s own CSS-SSV:

@server variables {
	primaryLinkColor: #AB6666;
}

a {
	color: primaryLinkColor;
}

If you wish to try out Shaun’s method, it is available through his CSS-SSV Page. Otherwise, let’s hope that CSS Variables are implemented quick enough so we can reap the benefit, optimize and save our time writing Stylesheets.


Don't like it? There are lots of published articles, pick a random one.

oCricket

Brajeshwar posted this article on Sun, Apr 20th, 2008 at 7:32 am
Categorized under Technology and has the following tags

Prev Article: Adobe AIR for JavaScript Developers

Next Article: Green-Screen Video Tips, Tricks and Techniques

Archives: Visit the Archives for more articles.

Comments Post Yours

There are 7 responses so far. You can follow any responses to this entry through the RSS feed. You can leave a response, or trackback from your own site.

  1. I have been after vars in CSS for some time for use with Flex.

    It would make it so much easier to create a palette of colors (or even a seperate stylesheet for the color palette) that are then re-used throughout the stylesheet and applied to component styles, instead of having to change the color value throughout the stylesheet.

  2. Really cool stuff.
    I never knew you could use variables in CSS.
    I don’t know because i haven’t tested, but why am i inclined to think that IE (All versions) as no support for this, oh, and maybe IE 8 has some support, but only if you include a specific IE 8 stylesheet with endless tweaking ;)

    I hate IE.

  3. why can’t microsoft make their bloody IE compatible with the latest css standards. Need to use so many hacks just to make one page cross browser compliant

  4. I have read several arguments for and against variables now and I understand why some are hesitant introduce another layer of abstraction. CSS is supposed to be for designers and HTML, PHP, etc. for the programmer.

    One case that I think is very strongly in favor of variables is with colors. You cannot even assign a color once for all elements doing it the ugly way because sometimes you are defining background, font, border, etc.

    I would support variables for colors only, and I think that would be much more widely accepted.

  5. I tried using css variables on IE 6.0 and firefox 2.0 (Mozilla/5.0) but I could get them affected.

    My code is:

    @varialbles
    {
    BackColor: gray;
    }

      .TestClass
    {
    border:1px solid red;
    background-color: var(BackColor);
    color: var(ForeColor);  /* ForeColor is defined in test.css */
    }

    Test Css Variables

    test.css
    ——–

    @variables
    {
    ForeColor: blue;
    }

    Only border property is applying but no other.

    Please suggest me how to get them work
    Thank You

  6. I Wish! That would improve the Web World so much! Great ideas!

  1. Pings & Trackbacks Sites, articles & blog posts linking back to this article.

Post yours

Sidenotes

Quick notes, scribbles, somehow related to this website and to what I do. Or perhaps I'm just plain lazy to make them into a full article.

Great Indian Developer Summit 2009

I got a Press Release of the upcoming GIDS '09 and here is an excerpt. The summit's program covers Java, REST, Unit testing, Groovy, Spring, Struts 2.0, SOA, Cloud Computing, Web Services, JRuby, RoR, Ruby, JVM, ...21st Jan, 2009

The flourishing gun market in Pakistan

VICE Travel: Darra, Pakistanby Top-Notch112 (Via: Deep Green Crystals) 20th Jan, 2009

Angry Ringtone for iPhone and others

[audio:http://audio.brajeshwar.com/angry-ring-ring.mp3] The ANGRY RINGTONE for iPhone. (Click the PLAY button above!) Download * iPhone Ringtone (.m4r) * MP3 Ringtone (.mp3) * Zipped (both .m4r and .mp3) To use it as an iPhone Ringtone; just double click the file "angry-ring-ring.m4r" and it ...15th Jan, 2009

IIM Ahmedabad's Leverage 2009

Leverage, the Venture Capital and Private Equity Club of IIM Ahmedabad and the Centre for Innovation Incubation and Entrepreneurship bring to you the 1st edition of the Venture Capital and Private Equity Conference on the ...12th Jan, 2009

Fedora 10 Released

Let's talk history! Fedora was created in late 2003 as a Linux based Operating System which gives the users an admittance from anywhere in the world to the most up-to-date free and open source software ...28th Nov, 2008

View the Sidenotes Archive

Play the Penguin Game

Recommended

  • Not Safe for Work Ever clicked a link and felt embarrassed with the content in front of your co-workers? Ever caught unaware because the funny link your friend sent was a little beyond funny? Let’s minimize that with NSWF.
  • AS 2.0 Reference Reference for ActionScript 2.0 Programming Language used in Flash. Primarily stashed here for my own personal reference.
  • Downloads All downloads, Free and Open Source.
  • Ode to Apple Dedicated to Apple - Mac, iPhone, iPod, iTunes, Quicktime, Apple TV and all the awesome softwares for the Apple Mac.
  • My Special Job My Special Job is a place where you can look for your weird necessities, strangely superb employees, when your need are more of those hackers, geeks, and ultimate rockstars in the Internet Technology.
  • o! Just Me Of colorful cultures, entertainment, media, life hacks, music, books and movies from hollywood & bollywood.
  • oCricket oCricket is about Cricket and people enthusiastic about it.

Download free Brajeshwar Wordpress Theme

Brajeshwar

Brajeshwar I firmly believe in keeping things simple, easy for users and I envison pushing the technical envelop time and again for the betterment of viable commercial and practical applications. More about me.

Brajeshwar's affinity with Adobe

My Photos

More photos on Flickr

Member of 9rules Network

Since its inception on 11th June, 2001, "Brajeshwar" has 949 Articles and 6,472 comments, contained within 22 categories and 1,497 tags.