Native CSS Variables: Welcomed Addition or Huge Mistake?

Native CSS Variables: Welcomed Addition or Huge Mistake?

The web development community received some big news recently. While not yet in the nightlies, experimentations are, once again, underway, which will, if successful, provide us with native support for CSS variables, mixins, and modules in browsers. The question is, though, is this a good thing?


Pros

  • Maintain projects easier
  • Write less “code”
  • More streamlined integration with JavaScript
  • Update site-wide settings and params with a single value change

Cons

  • Should CSS be complicated?
  • Higher barrier of entry for designers
  • The current proposed syntax will seem too confusing for some

How Does it Work?

Before we progress, keep in mind that these developments are still only in the experimental stages. They have not been implemented in any browser just yet.

If you’re modestly familiar with CSS preprocessors, like Less or SASS, you’ll have a basic understand of what to expect from these additions. (That said, the proposed syntax unfortunately is a bit different.) In the future, you’ll have the ability to create variables (global and local), and mixins, which you can think of as a collection of stylings that can easily be referenced.

What Took So Long?

As long as I can remember, the community has been clamoring for CSS variables; so what was the hold-up? In a word: disagreement. In fact, back in 2008, webkit was toying around with this feature — even to the point of implementing it into the nightlies — though, the proposal stalled not long after. Many felt that morphing CSS into a more programmer-like language would only introduce frustration; some even felt that it might confuse designers. For example, if the primary color in your project is stored within a variable — presumably at the top of your stylesheet — it would then require the designer to refer to two locations.

@myColor : red;
/* Less syntax */
#someElem {
 color: @myColor;
}

While this argument is valid to some extent, it doesn’t hold much weight. Most designers maintain a set of site-colors at the top of their stylesheet, which they use for reference. Introducing variables to contain these values is a logical solution.


The Proposed Syntax

Less or SASS fans will be accustomed to defining variables like so:

 
/* Less */
@primary_color : red;

/* SASS */
$primary_color : red;

The proposed syntax complicates things a bit by making variables typed. For instance:

/* Declaration */
 @var primary_color color red;

/* Usage */
body {
  color: var(primary_color);
}

Worth Noting

  • All variables are prefaced with @var
  • Variables are typed. Note the use of the color keyword in the code above.
  • To access the value of this variable, we use the var function, and pass in the variable name.

I must admit: it does seems a bit redundant to use the @var directive. The syntax that SASS and Less uses seems more appropriate and cleaner. @myVar is more succinct than @var myVar.

Variables types are a welcomed addition, on the other hand.

Variables are typed. Every primitive value type, every property, and a few extra convenience types exist. This lets us expose the new CSSOM stuff on them: document.styleSheets[0].vars['primary_color'].alpha = .5;
xanthir.com

Local Variables

Variables will also have the ability to be scoped to a declaration box, via the use of the @local directive. This can be useful when a variable only needs to be used once or twice within a project.

.box {
  /* Declaration */
  @local box_gradient background linear-gradient(top, black, white);

  /* Usage */
  background: var(box_gradient);  
}

Mix-ins

Mix-ins can be incredibly helpful. In fact, we covered the process of creating a class file of mix-ins not long ago on Nettuts+. You can read about it here — though keep in mind that the technique(s) presented in that article rely on on the Less preprocessor. The new experiments, again, use a slightly different syntax.

/* Less */
.border-radius( @radius: 3px ) {
  -webkit-border-radius: @radius;
  -moz-border-radius: @radius;
  border-radius: @radius;
}

/* SASS */
@mixin border-radius($radius: 3px) {
  -webkit-border-radius: $radius;
  -moz-border-radius: $radius;
  border-radius: $radius;
}

/* And possibly the native solution?? */
@mixin border-radius(radius length 3px) {
  -webkit-border-radius: var(radius);
  -moz-border-radius: var(radius);
  border-radius: var(radius);
}

Note the similarities between SASS and the proposed native solution for mixins. This is due to the fact that members of the SASS team are serving as advisors.

Nesting

As you may be aware, Less and SASS allow you to nest selectors. This can drastically reduce the size of your stylesheets, as it’s removes the need to the same selector repeatedly.

/* The current way */
#content { ... }
#content p { ... }
#content p a { ... }
#content p a:hover { ... }

/* Less and SASS */
#content {
  ...
   p {
      ...
      a {
         ...
        &:hover { ... }
      }
   }
}

/* And natively?? */
#content {
   ...
   @this > p {
      ...
      @this > a {
         ...
         @this:hover {
            ...
         }
      }
   }
}

While the proposed syntax is more wordy, to its credit, it does have a nice OO-like syntax, which will make plenty of developers feel right at home.

But remember – not all designers are developers.

Namespacing

By default in Less, all variables are — for all intents and purposes — global. As a result, it becomes difficult to distribute code, as existing variable names can be over-written. The potential native solution will be to implement modules, or namespaces. They can then be included in a block by adding the @use directive.

 @module Site {
   @var primary_color color #292929;
   @var secondary_color color blue;

   @mixin border-radius(radius length 3px) {
      ...
      border-radius: 3px;
   }
}

/* Incorrect Usage */
body {
   color: var(primary_color); // Variable name is undefined
}

/* Correct */
body {
   @use Site;
   color: var(primary_color); // #292929 (Works)
}

Conclusion

As noted at the beginning of this article, the documentation listed above is still in the experimental stages. It’s possible — likely even — that the syntax will change, based upon your feedback. So let’s have it. Does the idea of native variables in mixins in your CSS excite you…or scare you?

Me? Well I’m for it. I think the proposed syntax could use a bit of work, as it will no doubt scare away the designers among us. That said, if the syntax was simplified a bit, I’m 100% on board. How about you?

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.rebatesense.com RebateSense

    As long as all the browsers support these features that would be nice and would reduce a lot of clutter from the messy CSS files. Any hacks to comply with a few browsers would kill the deal. Looking forward to a better CSS experience.

  • Etienne

    I like LESS syntax much better.

    Simplicity is never a bad thing.

  • http://www.tonycoculuzzi.com Tony

    This excites me. Hahahaha
    I think native CSS variables would be an amazing addition, but like the author stated I also think the syntax should be slightly more simple like that of LESS more so than SASS. Regardless, the fact that this is in the works makes me pretty happy. As a programmer and web developer I can see this being so useful in so many ways. :)

  • http://www.jakswebdesign.com Adam

    It’s so easy to do this exact same thing right now using a small (yes, very small indeed) amount of server side scripting, it seems silly to build it out into the CSS spec in my opinion. Simply because we all know how fast (er, slow) the advancements in this industry move down to the actual level of Joe-user. If you want to use CSS variables, set up a php script that holds your variables and outputs plain CSS-text and serve it as text/css to the browser……the abstraction of this technique is so minor indeed, to rebuild the css support (even if it’s not difficult) and have it take years to filter down where everyone can use it – and until then have to support multiple implementations (browsers that accept vars, those that accept them in X or Y format, but not in Z, and those that don’t accept them at all) is just plain dumb in my opinion.

    CSS “vars” could be accomplished years ago with a very minimal server-side overhead, those of you who have been waiting for the day when CSS variables exist, you missed it, it happened a long time ago just in a different form, well before even LESS and Sass. No need to change the spec, it’s just over-complicating a really simple syntax and creating more and more convolutions for browser and web developers.

  • Joe Kennerly

    The only thing that seems to be questionable to me is whether it will require fall back to older browsers. Which, if not, makes something like Less or SASS more appealing.

  • //adrusi.com/ Adrian

    Honestly, I don’t see what the problem is with making CSS more complex, unless it makes it slow. This would all still be just a superset of CSS, all currently valid CSS would be valid, so if a designer doesn’t want to use it, they don’t have to.

    I can also pretty much guarantee that people won’t be using this for a long time after it gets implemented (if it does). With so much controversy over the concept and syntax, browsers will implement it differently if at all. This will be adopted long after CSS3.

  • http://studentkak.se Anders

    I have been longing for css variables. Although, i have to say that the “current” syntax is a bit wordy at first sight.

    Then again, variables might need to be hard typed to make sure client side “compilation” is fast and correct. Also, you want be declaring variables as often as you are when you’re programming…

  • ClubAJAX

    I find it fascinating that of the 50 or so comments, only one person is opposed to the idea (and kudos to him for the alternate view). And yet this proposal still languishes? Because it’s being implemented by academic standards morons who think themselves into a corner.

    We need variables!
    Oh, we should be sure they are declared with “var”
    Oh we should add strict typing.
    Oh we should allow them to be local.
    Oh we should add math.
    Oh we should add scientific notation.
    Oh we should add algorithms.

    Wait! Algorithms are too complex! Therefore we cannot have CSS variables.

  • http://grapheffect.com Chris Lorenz

    First of all in theory I think this is great. I have been using Less for some time now and it is great tool. They need to seriously rethink the syntax though for native support. It is silly to add that arbitrary code to do the same thing. Making it native should also mean making it simpler.

  • Edward Longman

    Loving it in general except that i much prefer the .less way of doing border-radius( @radius: 3px ) to the .sass way of doing it.
    otherwise great

  • http://www.davidsparks.me David Sparks

    With CSS being so stupid easy in terms of I think the syntax needs to be streamlined. imo it would be a mistake to allow Less and SASS to do the same thing in an easier to understand and use manner.

    aside from the syntax needing to be simpler, i love it.
    Variables are about as easy as it gets with more advanced languages. I wouldnt mind some if logic down the road too but that can get much more complicated. variables are usually more what you see is what you get.

    Nesting sounds great too, i’d love to have that natively.

    For it.

  • Paul

    Nesting is great idea, but @this completely brokes it. We can kind of nest rules now, but unfortunately only for one level:

    @media screen {
    .myClass {
    some rules
    }
    }
    @media print {
    .myClass {
    different rules
    }
    }

    So instead of adding @this to make programmers happy, I think it would make more sense to simply allow current nesting for more than one level.

    There is an inconsistency in your example:

    a {

    @this:hover {

    }
    }

    :hover is pseudoclass, it’s not an element inside “a”, so it shouldn’t be nested:

    a {

    }
    a:hover {

    }

    You didn’t write example for using mix-ins. I think Less and SASS example for using mix-in is ugly, it would look better if it was a property:value pair, but that create’s another issues.

    Last but not least – I don’t like variables idea at all, but IMO proposed syntax makes much more sense than Less or SASS – it’s familiar with @import and it looks like CSS. Less example is messy, while SASS is absolutely terrible! It looks like invalid variable declaration in PHP, very easy to mistakenly use : in PHP and = in CSS, I can see those programmers tearing out their hairs ;)

  • http://calebevans.me/ Caleb

    I feel there’s a place for variables in CSS, but the syntax needs be simpler. The syntax should try to be as close to the standard syntax as possible:

    @my-color: “red”;
    @shadow: “0px 1px 0px #000″;

    body {
    background: @my-color;
    box-shadow: @shadow;
    -webkit-box-shadow: @shadow;
    -moz-box-shadow: @shadow;
    }

    Anything else would introduce too much complexity for a language that needs to remain simple.

  • http://www.stevendavisphoto.com/prints.html Steven Davis

    YES YES YES! I want it NOW! It may be harder to grasp for news, but they can still use the current formatting too.

  • http://www.stevendavisphoto.com/prints.html Steven Davis

    YES YES YES! I want it NOW! It may be harder to grasp for newbs, but they can still use the current formatting too.

  • Amy Lo

    I agree this is a great idea.
    It would save a lot of time in the long run.

  • http://www.macrogalaxies.com/ Shane Perreault

    I think one of the great features that this would provide would be allowing users to style their own pages through a user control panel. So if you have a website where people can design a profile page background, you can have this in the html of the page.

    @primary_color : primary_color; ?> ;
    @secondary_color : secondary_color; ?> ;
    @background_color : background_color; ?> ;

    body{

    background: @background_color;
    color: @primary_color;
    border: 1px solid @secondary_color;
    -moz-box-shadow: 0px 0px 5px @secondary_color;

    }

    This way you don’t have to embed a bunch of php or whatever language you choose do.

    • http://www.macrogalaxies.com/ Shane Perreault

      Sorry, fixed code.

      @primary_color : <d?= $profile->primary_color; ?> ;
      @secondary_color : <d?= $profile->secondary_color; ?> ;
      @background_color : <d?= $profile->background_color; ?> ;
      body{
      background: @background_color;
      color: @primary_color;
      border: 1px solid @secondary_color;
      -moz-box-shadow: 0px 0px 5px @secondary_color;
      }

      • http://www.jakswebdesign.com Adam

        I don’t understand why everybody is getting blinded by the ability to do this if this new feature of the spec ever gets picked up. You can do this NOW, you could do this 5 years ago – just use a php file that serves text/css in place of a css file and voila, CSS variables!

      • http://about.me/mikeschinkel Mike Schinkel

        By your same logic, why use anyone else’s software for anything? Code it all in assembler by hand!

        The value is not in any one person being able to do it with a one-off syntax, the value is having everyone move toward it with a common syntax. Yes I could do it in PHP, but I can’t get everyone coding a WordPress theme I might want to use to do it, so in many cases the fact I can do it on my own is abstract, esoteric, and quite frankly, not useful at all. It only because useful if others are doing it.

      • http://about.me/mikeschinkel Mike Schinkel

        That last reply of mine was for @Adam, not for @Shane.

  • http://leonpaternoster.com Leon

    I don’t see a problem with the current system: keep CSS a simple, declarative language that’s easy to pick up, and use LESS as a ‘plugin’.

    Unsurprisingly, the response on a forum with a high developer readership is largely in favour, but that’s not the only CSS audience.

    • http://about.me/mikeschinkel Mike Schinkel

      @Leon – The problem with your approach is very few mainstream web apps (such as WordPress or Drupal) are using Less built into their core which makes LESS pretty much a non-starter for anyone using such an app.

  • Matt

    I don’t think this complicates things at all. What complicates things is having to remember the widths and color codes your using throughout my projects. These are welcomed advancement that I’m sure will be delayed by Internet Explorer for 10 years or so.

  • Miguel

    Bring it on! But IE will probably be late to the party anyways :(

  • Alex

    So interesting to see the pace of technology in the last few years. The browser is really getting some attention and the development community has such a strong voice that resonates in things actually being changed.

    I’m happy to see CSS get some love. Changes that help and don’t hurt developers are always welcome, can’t wait to see this finally implemented.

    P.S.
    I like sass syntax best (not scss but sass). Its clean and more precise, reminds me of ruby.

  • http://www.ninesixweb.com Evan OConnell

    I don’t think this effects beginners as this article suggests. If they find them too complicated then they don’t have to use them. I do think however, that this will save a lot of us time while we are initially designing a site; no more find and replace all.

    I think this falls right in line of what CSS has already done. Classes save us time by not having to style common elements on our page. This will save us time by allowing us to change common values within our classes in one place.

  • http://paulirish.com Paul Irish

    Tab Atkins, the author of the original slides has blown out full notes in a blog post today:
    http://www.xanthir.com/blog/b49w0

    Has some clarifications and slight changes.

  • http://www.umbraprojekt.pl mingos

    Whoa!

    @this > a {
    @this:hover {

    I’m speechless. I use LESS and I’ve been missing something like @this all this time! Right now, if, say, I want to style a tag wit hand without a class, I need to do it in two separate blocks:

    a { color: red;
    :hover { color: white; }
    }
    a.active { color: orange; }

    now I’ll be able to do it in a more readable way.

    a { color: red;
    :hover { color: white; }
    @this.active { color: orange; }
    }

    Good stuff, can’t wait to use it!

  • http://www.ronniesan.com RonnieSan

    I think native CSS should be exactly like the LESS syntax (perhaps with $ instead of @). It saves file size and makes so much sense.

  • http://www.artillerymedia.com John Wooten

    Totally for it!

  • Irfan M

    I do not think this is a bad idea at all. It makes CSS more complicated than it needs to be and harder to read.
    I understand that one can make their own variables in most other programming languages, but CSS should remain the way it is :-)

  • Brad

    Seems to me this would eliminate accidental repeating of elements and conflicts on the CSS file

  • http://www.breakthenetwork.com Matt

    I think this is a positive improvement. If designers wish they can still write stylehseets in the traditional manner, but for larger more complex sites programmers will have a whole new toolbox to work with.

  • w1sh

    Css is pretty easy already. It’s CSS layouts that are confusing to most newbs. So definitely include this feature in later ver of CSS (lest we all go LESS), and [W3C] if you really care about simplicity, then write a friggin’ tut on how CSS layouts work (especially vs tables).

  • w1sh

    Gonna go ahead and bother you here too since you hate me already.

    Why is Burak stopping his Codeigniter tuts? They were priceless and would continue being more pricelesser as they grew into one big, beautiful, cohesive strat for building sites with CI.

    Burak – love your tuts, please bother Lynda to make a CI series. ;)

  • http://twitter.com/agilius Vlad

    I think css vars and namespaces should be added into this language because it will give coders more power. Those who don’t know how to use variables will just use the normal way of adding proprieties, while more experienced users will have their way much faster around the CSS code.

    Let’s think ahead and see how well css variables could work with PHP generated css code and dynamic/condition-driven layout states for web interfaces that go beyond the normal website functionality.

  • Bogdan

    I`m for it! In this way we could have CSS files more organized. For large projects it will be very good. I will like some cross browser conditions in CSS, like if, for or switch that can be very helpful in some cases.

  • http://webpresence.bg IsHristov

    I don’t like it the way it is proposed now. Although I’m not using LESS or SASS, their syntax is WAY better! It’s not supposed to be that complex as they want to make it.
    Less is more, as it was already commented.

  • http://intrepidstudios.com/blog Kamran

    I am a fan of variables because I am a developer/designer and I’ve always been frustrated why CSS doesn’t let me reduce redundancy in my stylesheets.

    What I don’t like is some of the proposed syntax; I understand LESS’s syntax better. I think with more work, this could be great.

    The problem will be, of course, that LESS and SASS have a distinct advantage: they translate it back to CSS2/3. This native method will only work with browsers that implement it (AFAIK, I guess I haven’t read the spec so ignore this if I’m off base)… and we all know how long full standardized implementation takes! *cough*never*cough*.

  • http://justsimplycreative.com/ J. Canfield

    I love it. I will admit that the simplicity of CSS probably has allowed many new designers to understand and get involved, but they still will be able too — just with more advanced features. I have been using SaSS/Compass for the last few months for the reason of variables and mixins. I love the concepts and as a developer, it speeds everything up tremendously. I am all for this move.

  • Brandon

    I love this idea, though I do think the syntax needs a little simplification. My only fear is how well this will degrade for older browsers that don’t support this feature of CSS.

    I’m not too worried about designers not being able to take advantage of this feature of CSS. Many designers don’t understand or don’t take advantage of every aspect of CSS, and that doesn’t have to change.

    Though people tend to see it as a relatively simple language, CSS is actually already quite complex. I’ve heard it put really well before: “CSS is simple to learn, but difficult to master.”

  • http://gravitymad.com Travis Millward

    People will abuse anything. I don’t think throwing this at css will help much, personally. To me, it’s all about being strict and simple. If you are defining a color on a style sheet so much that it would be easier to just have a variable to do it. Maybe you should get a bit more creative with your use of css? I dunno though, on the other hand, it would be cool to at least try it out on a project and see how it goes? Seems like it might promote the use of over coloring everything just because you can. What I do is create a class…

    .fillA {
    background: #cf3c3c;
    border-top: #9c0f0f;
    }

    Then any time i want that type of fill in the page i just call it from the html.


    </div

    submit

    Obviously this is a broad example, but… typically in my css library I will have 2-3 of these fill type classes.

    • http://gravitymad.com Travis Millward

      Dang, I forgot to replace my “” with < and > so my example broke. but.. you get the picture right ? :)

  • http://www.zerozaku.com Gio Borje

    I agree with Kamran. Using SASS and LESS as compilers work well because if CSS becomes a programming language, might as well use the compilers.

    On the off-note, we should just have IDEs that compile SASS/LESS syntax into CSS2/3. Maybe create a higher-level CSS language that compiles into CSS. Who knows what we can do with higher-level abstractions of colors and relative positioning? It could work well with some browser-based physics engine.

  • http://pixby.se Filip Stefansson

    “some even felt that it might confuse designers”

    They don’t have to use variables, so I don’t think it makes CSS any tougher to learn. Variables are very welcome imo.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      The idea is that designers would potentially inherit these sorts of stylesheets, which do make use of them.

  • http://banhawi.com/ Banhawi

    i see that css variables is a great addition .

  • Jordon

    Agreed, CSS is already easy. However I have never took the full time to learn it, I can understand it. With this improvement I can still understand the CSS just fine. Seems like you could do more with the code if it was changed. Thats just my opinion though. I am for the change.

  • Ryan

    Anyone who asks if CSS is too complicated with variable names hasn’t inherited a large corporate application. Redesigning the style layer is nigh impossible in any reasonable time frame without them unless you simply want to keep the old design and change red to blue universally.

  • Thera

    I like LESS, however one very common case where I still have to use a script is conditional statements.

    Even a simple IF..ELSE would open a whole lot of new possibilities as far as I’m concerned.

    (I never tried SASS however)

  • Cogito

    I remember the article here recently about Less.js, and I remember thinking “Nah, I don’t wanna use something that cool that is that fallible (being that it’s JavaScript)”. But I think native support of CSS variables and mixins and such would be a maaaajor positive boost to the way we design, the way we get things done project wide.

    As for the syntax, I don’t see what’s wrong with it. Designers will have no problem getting used to it, as, if they’re smart, they’ll realise the scope for time and space saving with these.

    I really hope they get implemented, and soon, I can’t wait to “mixin” these new techniques. *drum roll* Hehehe. :P

  • http://www.kavamediagh.com Yaw Lartey

    I think this is a great idea. i am all in for it. This is what we have been waiting for. It is long overdue!!

  • http://www.activo.com/ Activo / Ron Peled

    So, I would be very interesting on the performance impact that this feature may have on the browser rendering speed. This may just be one more thing we will have to worry about as far as rendering speed in users browsers, not to even mention different browsers implementing this differently and how that would play out…

  • Jason Shallcross

    I’ve been after CSS variables for years – but I don’t like the above syntax which seems a bit too wordy.
    It should be flexible, so please, let’s not have strict variable typing!
    I also think there should be some way of marking the end of the variable name.

    So how about….

    @define {
    color:#ff0000;
    theme:red;
    width:200px;
    }

    div.theme_[theme]_box {
    width:[width]
    background:url(/images/[theme]_bg.gif);
    border:1px solid [color];
    }

    You could also do namespacing:

    @define:myTheme {
    color:#ff0000;
    }

    p {
    color:[myTheme:color];
    }

    of if you prefer dots:

    p {
    color:[myTheme.color];
    }

  • http://tonybarnes.me Tony Barnes

    Sounds great – looking forward to using this in future projects!

  • http://blog.arosas.me Andres Rosas

    Hopefully IE and all the other browsers should support it. Because adding some simplicity won’t hurt in fact it will help reduce the development time drastically. As a programmer and aspiring web developer it would be only a small adjustment.