Dave Woods - Freelance Web Design Warwickshire

CSS Variables

It’s something that many people have been asking for and wanting for some time now and finally it looks like variables are going to be making their way into CSS.

I first heard the news from Peter’s blog over at Broken Links and thought it would be of great interested to most of the readers here.

Essentially, you’ll be able to declare a variable in your CSS using the following syntax

@variables { keyColor: #f00; }

And then you can call this variable wherever you need to use it in your CSS by using

h1 { color: var(keyColor); }

Presumably using this method you’ll be able to declare all your colour scheme in a bunch of variables at the top of your CSS

@variables { firstcolor: #f00; secondcolor: #300; thirdcolor: #300; }

Sounds like it’s going to be an extremely useful improvement within CSS and something I’m sure that anyone who deals with CSS will be eagerly awaiting.

26 comments on “CSS Variables

  1. Jason

    CSS is not a programming language. Adding variables will just increase the complexity of an already complex markup scheme. Adding variables also adds an extra step for parsing and executing the stylesheets client-side. That translates into increased load times for the end user. This is even more unnecessary when you consider the usage of variables in CSS. Where is there a situation where CSS variables would be a better fit than simply parsing the styles on the server-side using an existing scripting language? In that case, the result could be cached anyway, decreasing load on the server and the client. If you need scripting on the client side, use the existing language: JavaScript. In short, variables were never added to CSS because they were simply never needed.

  2. Benjamin

    Umm… the weather is also not a programming language, but it does have variables. Is Jason’s complaint simply that CSS is hard? I wonder if we called them CSS macros instead of CSS variables, would that make them acceptable? How does JavaScript make it easier?

    I look forward to being able to declare obscure colors in hexadecimal with a name at the top of my stylesheets and using the name throughout the stylesheet.

  3. Dave Post author

    Personally I think it’s a good idea and obviously if people don’t like it then they can use the existing methods and can quite easily use a find and replace to edit CSS.

    I’ve had a few occasions when it’s been decided at a late stage that a grey is slightly too dark or that a red needs tweaking slightly and I feel that this would be the perfect use for CSS variables so that one change at the top of a CSS file can change all those colours within the page.

    CSS is cached after the initial visit anyway so I can’t see this method causing any problems for users in terms of load times unless someone creating the CSS really goes overboard.

    Personally, I’d probably only use it for the main two or three colours of a design and will continue to define individual colours for other elements but for common colours, width’s etc I think it might be extremely useful.

  4. Matthew Vines

    Personally I am more interested in CSS expressions.




    /* non-existant to my knowledge */
    width:expr(var(page_width) – 20%;)

    this way, if and when I decide to change the overall width of my fixed width page, I don’t have to hunt down and re-calculate the width’s of any other elements, just change the variable value at the top of my stylesheet.

  5. Matthew Vines

    edit: my expression is a little jacked up (20% of what), but hopefully it is clear what I am getting at.

  6. Dan Dorman

    Yep, variables in CSS would be rad! In fact, it’s downright lame that colors, fonts, et al. can’t *already* be declared at a global level and easily re-used.

    The bogeyman of supposed longer load times is ridiculous: why would having the variables be parsed by the browser be so terribly slower than using some other scripting language on the server? Heck, having the browser parse it could very well be faster–geez, the browser’s already parsing the CSS as it is. Why should this sort of information, which is intrinsic to the style data, be relegated to getting parsed by Ruby or PHP?

    It’s also more portable if the variables are within CSS; you don’t have to rely on your hosting environment being set up to parse your scripts.

    The only practical drawback, as with so many CSS issues, is broad browser support. What’s the use of nifty CSS variables if not every browser implements them? (I’m looking at you, Internet Explorer!) This is where cheesy hacks like parsing CSS files on the server comes in handy. Plus, there’s a small case to be made for caching the result on the server, but that doesn’t outweigh the benefits of across-the-board CSS variable support. No way.

  7. Jermayn Parker

    I can see benefits and disadvantages to both sides, either way it sure will be interesting to see how it goes but then again who is holding their breath for this to happen? I know I am not!

  8. Pingback: CSS3: css variables are a bad idea. Just allow us to call other selectors. « Rip’s Domain

  9. Matt Giuca

    I don’t get why people are complaining about this. I have been saying for years and years we need variables and expressions.

    I should qualify what I mean by this (and what I think the article means by this) – since people seem to think this will transform CSS into a scripting language like JavaScript – IT CERTAINLY SHOULD NOT.

    By “variable”, I really mean “constant”. Or “macro”. Call it what you will. I mean you should be able to declare “bgcolor1 = #33f; bgcolor2 = #66a; textcolor = black”, and then use those constants everywhere in the CSS. Then if I want to change the colour scheme I can do it in one place and not have to find-and-replace #66a all throughout.

    If people wrote software the way we write CSS (hard-coding numbers everywhere), they would be fired. Yet we’re forced to do it in CSS.

    And yes, we need expressions too. We need to be able to say “width: #topbar.width + #sidebar.width”. I am sick of having to do calculations manually, then write the results in, once again hard-coded, and have to manually update them when everything changes.

    No, I am not being lazy. I’m being a good programmer.

    I’d prefer the syntax to not be so obnoxious – @variables { … }.

    It would be heaps better if I was simply able to write, at the top level

    myvar = value;

  10. Andrew Maxwell

    I am excited to hear about this and I hope it goes through, being a programmer and then writing CSS just seems odd and always has. As far as the browser problem with IE I think it will change with IE8 now leading the way with version-ing which is something I have been wanting for more then 5 years.

  11. Pingback: Cómo declarar variables en CSS 3

  12. Pingback: dtsn : JavaScript in CSS, ugly, but intresting

  13. Naren

    Let me know whether this variables works in all PC browsers
    Thanks in advance

  14. Dave Post author

    Hi Naren, this is only propsed for future CSS so definitely isn’t in use yet although I think I remember reading somewhere that a nightly build of Safari had implemented it.

    In any case, it’ll be years before all the common browsers (especially IE) have implemented this successfully.

  15. James Hopkins

    @Dave: An implementation (based on the initial proposal draft by Hyatt/Glazman) was incorporated into Webkit nightlies from March ’08 to around September time, but was removed due to concerns regarding feature adoption by authors (and therefore reliance) before the spec had any time to mature.

    If any of your readers are interested, I’ve published an article (http://www.css3.info/summary-of-the-two-current-css-constants-proposals/) summarising the initial spec, and a counter-proposal that has come about.

  16. Pingback: JavaScript in CSS, Ugly But Intresting | dtsn

  17. Gerrit

    Another interesting issue is to use PHP-Script for your CSS files. You can put in as many vars as you like and even change the look of your site depending on almost everything ;-)

    just make a php-file and change headers to css

    header(“Content-type: text/css”);

    this is really thrilling!


  18. Гамлет

    Интересно. Вообще чтение вашего блога это не просто глупое просматривание новостей или чтениебреда про то, чем человек сегодня занимался, а нахождение реально занимательной информации.

  19. Prakash

    Hi, I used this variable substitution and checked but no result. am using ie6 and firefox 3. anything i have to include for this to work?

  20. Dave Post author

    Hi Prakash. It’s not available to use yet but is proposed for CSS3 so hopefulyl we’ll see it at some point in the future.

  21. Sitin

    The only advantage of CSS variables is to use their definitions in separate files. In this case we can divide “static” and “dinamic” parts of the style. It saves some server-side time avoiding css parsing for simle task. And if it is not (the variable scope is only curent file) I agree with Jason that styles must be simple to implement on the client side and css is not a programming language.

  22. rolfen

    The current alternative is including PHP code into you css, or doing extensive replace every time you want to change a common color.
    CSS was originally take away style from HTML and centralise it in a single place. Variables only take this further.
    Performance has never been the primary concern in web technologies, whether it is a good thing or now, I dont know.

  23. Voynex.com

    As for me it is better to call those macros then variables and I would suggest more scalable solution – add the inheritance of the CSS classes.

  24. James

    For simple variable colors creating variables for css is not necessary. If you need this simply right your css code in php and include it into header as a style tag. You’ll achieve the same. Albeit, I can’t count how many times I wish I could dynamically have a variable with the screen width to make things go faster. As for people saying this would have a ton of overhead. I really don’t think so. After all, so much is already calculated on the fly as it is. If you think about it width:100% is already technically referencing a variable. I believe css itself as itself has more complexity than a coding language. I would rather draw a website in Java then html+css it.

    Give it a while, and eventually flash will start to encompass entire sites page spaces rather than just the limited content they deal with now. Why? its easier to get what you want on the page with limited overhead.

  25. Tarn

    The simplest way to show that CSS needs some form of variables is to take a medium complex, fixed 3 column layout of some guru, and ask some other guru to increase the column width of the middle column. Then stand back and watch the fun.

    Some people think that littering a CSS file with numeric constants is somehow ‘pure’, while using expressions would be ‘bad’. Such people should demonstrate how, without variables or expressions, this philosophy can be used to make and maintain any significant program – perhaps a CSS parser ;)