Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
CSS Variables landing in Chrome 49 (developers.google.com)
186 points by wanda on Feb 7, 2016 | hide | past | favorite | 63 comments


For those commenting about SASS having this forever etc, note that this goes a step further:

    :root { --color: blue; }
    div { --color: green; }
    #alert { --color: red; }
    * { color: var(--color); }
You can't accomplish that with SASS today. More info [0].

In fact, this feature isn't even covered with cssnext:

    The current transformation for custom properties aims to provide a future-proof way of using a limited subset (to top-level :root selector) ... [1]
I'm very curious whether or not this paradigm will be accepted as "best practice", or how it will be used.

[0] https://developers.google.com/web/updates/2016/02/css-variab...

[1] http://cssnext.io/features/#custom-properties-var


Don't forget that CSS Variables can also be used within media queries.


And if you change a CSS variable in JS, it will recompute all of its uses.


If you're interested in seeing what happens next with CSS Variables, check out the CSS Houdini project https://drafts.css-houdini.org

It starts with a JS API for more control over CSS Variables (which are actually called Custom Properties), and then goes into APIs for custom renders and even custom layout engines, all controlled via JS + Web Workers


Also on the topic of things SASS cannot do:

Custom Properties effectively enable "styling APIs" to be declared for Custom Elements that have a shadow root, since Custom Properties cascade across shadow boundaries (detail in parent's [0]).


They're already enabled in Firefox, and they'll also be supported in the next version of Safari.

I'm going to use these to allow changing the appearance of my app, which has a Windows 95-style UI. 95 has many customisable values that determine how the UI looks (fonts, font sizes, font styles, foreground and background colours, UI element sizes, etc.) that it stores in certain registry keys and that the user can change from the Display control panel applet. In my app, I'll be using CSS variables in place of registry keys.


you are using reg keys to store properties? is it a chromium app?


He was just explaining how it worked in Windows 95, he will be using CSS variables instead.


She, and yes, that's the idea. I couldn't explain it very clearly.


Sorry, I always default to the male form for some reason.


I've wondered for years why we're using pre-processing to get variables into CSS. Given that there hasn't been a commonly advocated workflow that didn't include some sort of CSS processor (like LESS or SASS) in about a decade, it seems like somebody working on the standards would have realized that CSS needed variables, at the very least. So, it's cool that it's coming, though it's taken a lot longer than I reckon it probably should have.

I would normally say, "But, at least there's been time to work out the syntax in non-core projects, so things are probably nice now." But, this syntax and behavior doesn't even resemble SASS or LESS. Is there some other tool out there that provides variables in CSS that this is modeled after? Why reinvent the wheel when so many people are already familiar with and have worked out the quirks in SASS or LESS?

Reading the explanation for why they went this way (in short, because these are nothing like SASS variables, in the sense that SASS is more like a macro): http://www.xanthir.com/blog/b4KT0

Is somewhat unconvincing. Why not implement what's already working for people in SASS/LESS (in the way it's already working), and then move on to whatever it is they've implemented here later once it is clear it's something people want/need and once it's been worked out in pre-processors? (I don't think I quite grasp the entirety of the difference, either...is it merely a matter of scope and composability?).

Actually, someone in the comments maybe sums it up:

"In fact, let me see if I've got this straight in my head:

CSS preprocessors added a feature called variables, but which would more accurately be described as macros.

Browser vendors and the working group worked sporadically on an in-browser implementation and standardisation of this macro feature, and they also called it CSS variables.

The WG's focus shifted to a feature more akin to custom properties, but which retained the name CSS variables.

So, right now we have CSS variables in preprocessors, which are macros, CSS variables in browsers, which are custom properties, and maybe at some point in the future, macros in the browser, and actual variables in the browser." (Source: http://www.xanthir.com/b4KT0#4KT0-13 )


The CSS team has people like this, who no longer make websites: https://www.w3.org/People/Bos/CSS-variables Thus they're disconnected from current web developers.

Meanwhile Smashing says something like 77% of audience uses SASS.


Ah, Bert Bos, the W3C's "style activity lead". What a joke.

He's the guy who wasted a decade writing an ASCII-art based "template layout module"[1], which he was never able to persuade a single browser vendor to implement. It eventually got demoted from a working draft to a "note", which is the W3C's polite term for standards fanfiction.

His other major achievement is putting his own photo on every one of the CSS working group's web pages. I'm not joking: https://www.w3.org/Style/CSS/#endmatter .

And let me tell you tale of that photo/byline. It originally appeared on the working group's crappy 1990s site, which persisted until the late 2000s (because that's how fast things move at the W3C), and you could kinda forgive it as one of the dumb things people put on dumb 1990s websites.

Anyway, eventually it became too embarrassing that the working group responsible for CSS had such a shitty site, and some other members of the group took it upon themselves to produce a shiny new design with useful content, but sans Bos' photo. This done, they submitted what they'd come up to the W3C. Eventually, it showed up on the W3C's servers but, surprise, surprise, it had been rather mangled, and Bos' photo was back, clumsily shoved into a footer where it hadn't originally been.

It's a small, petty thing, but all the more hilarious for it. God knows how that guy still has a job at the W3C. Maybe he's best friends with Tim Berners-Lee, or something?

[1] https://www.w3.org/TR/css-template-3/


To be fair though, I should also say that nowadays the CSS working group has a lot of very smart people who absolutely understand the needs of web developers/designers, and have been tireless in getting things like Flexbox specced and implemented across different browsers.

CSS is about a decade behind where it should be, but that's not the fault of the people working on it now. And I think its future is actually comparatively bright, especially with the Houdini project taking off.


> He's the guy who wasted a decade writing an ASCII-art based "template layout module"[1], which he was never able to persuade a single browser vendor to implement. It eventually got demoted from a working draft to a "note", which is the W3C's polite term for standards fanfiction.

This is because it was absorbed into the larger and more fleshed-out Grid specification, which is nearly release-ready in multiple browsers. The ASCII art is actually really useful!


> Very few people (only professional designers, it seems) write style sheets longer than a hundred lines.

Hahaha, wow.


As someone who has to write thousands of lines of CSS due to a poorly designed CMS, I'll start calling myself a Professional Designer from now on.


That's from 2008, though that was a pretty silly thing to say even then.


That website is a stunning statement of the author's CSS skills.


Didn’t Firefox have actual SASS support for some time? I think at least the dev tools had support for SASS source maps, but I’m not sure if the browser actually had support.


Source maps aren't specific to SASS; you can use them with any tool.


Properly, the --foo stuff is a Custom Property. You can use its value as a variable, with var(), but it's not the only use custom properties have. That's why the spec's full name is "CSS Custom Properties for Cascading Variables". But that's a horrible mouthful, so "CSS Variables" is what it's usually called. (Plus that's the shortname in the url.)

(There's also a large focus, in v1 here, on the variables use-case, because that's what I needed to sell it to the group at the time. The CSS Houdini Task Force is now expanding Custom Properties properly, so they can actually be used for random JS things without a ton of hackery.)


custom props beginning with 2 dashes is slightly annoying given the BEM syntax has already grabbed that as Modifier...

  .foo {
    &--bar {
      --bar: 0;
    }
  }
It's a pretty contrived example, but akward to comprehend at first glance.


The syntax is verbose and ugly compared to SASS


I think a lot of people agree with you but there is a reason:

http://www.xanthir.com/blog/b4KT0


I understand the reasoning, but this new syntax is still kind of verbose and ugly. I think one of the reasons Sass has been so successful is that it is elegant. It adds a lot of functionality to CSS, but does so in a way that feels very much at home. This new syntax doesn't feels very elegant and it doesn't feel at home with current CSS syntax.


If I'd done what everyone keeps saying I should have done and just used $foo, then Sass would have gotten angry at me, because we'd be sharing syntax for different features. We already tweaked CSS a little to avoid that in another case (when specifying grid line names in Grid, you surround the names with []; it was originally (), but Sass asked us to change it because they use that for their list syntax).

We could only have used $foo if we hewed very close to Sass's functionality - global macros that operate at the stylesheet's lexical level. That wasn't what we wanted to do, though, either at the time (considering only the variables use-case) or looking forward (to the use of custom properties as the generic "inject info into your page via the CSS engine", a la data attributes for HTML).

By avoiding global macros, we also get context sensitivity - we can actually offer APIs for this stuff that are smarter than "here's the string you set". When we add custom pseudoclasses, custom media queries, etc they'll all get their own useful APIs. Sass is stuck with string manipulation, because you can use a Sass var anywhere, so it's impossible to infer anything about it.


Stupid decision, the should have used $foo (dollar sign for variables) like in Perl and PHP. It remind me decisions of standards based on XML (XLST, XML-Schema, RDF, etc).


Read the linked post. Css variables are nothing like macros like sass's `$foo` and css might support macros with sass's `$foo` syntax in future.


I read the article, that's why I commented because "might support something in future" that probably never happens, is what I related to XML based formats design decisions go wrong. Argh, but thanks for misunderstanding and downvotings.


Ok, that's cool. How long until we're able to use this and not have to worry about browser incompatibilities?


You can use it today with the help of http://cssnext.io


You can use a limited subset. cssnext isn't magic, it's purely a source transformation, there's no runtime. It can't handle the dynamic part of css variables.


Yeah, CSSNext here is basically the intersection of CSS variables and Sass variables - you can only use them in property values (like CSS), and you can only declare them at top-level (like Sass).

It's nice if you really want to utilize the current syntax, but it's less powerful than either option it's derived from.


Wow, this is awesome! I can't believe I haven't seen this. Thanks for pointing it out.


It depends on what browsers you need to support. Based on this data http://caniuse.com/#feat=css-variables I think it will be quite some time before you see this in sites that need broad browser compatibility. Surely there will be (is?) a shim that will come along.


I have a plugin that adds the ability for CSS to retrieve variables and values from regular JS!

It works in every browser today, and even old browsers, INCLUDING IE8!

http://elementqueries.com/demos/variables.html


~5 years depending on who you're targetting.


Pretty sad that in a world with living standards and silent updates, things that improve the state of the Web so vastly for developers still take so long to be widely available. (W3C doesn't even have a CR yet.) Less and Sass are nice, but the resulting CSS is full of repetition, thus hurting performance.

Am I right in assuming that IE won't receive any more feature updates? Many enterprises will stay on Win 7 for a while and enterprises traditionally embrace IE, so thank you, "new" Microsoft, for pushing things forward.


Given that Edge has pretty much completely replaced IE, then yes, it's unlikely IE will receive any more updates. And to make it worse, Microsoft doesn't seem to be updating Edge as much as they were promising, meaning that we could end up in the exact same situation as before.


Edge is an evergreen (ie auto updating) so it's a very good thing that MS is aggressively pushing to kill IE. In the not-so-distant future, IE won't exist.

Safari will likely be the next browser that will be slowest to update, considering its current progress in relation to the latest standards. Even with regular updates they seem to be falling behind.


> aggressively pushing to kill IE. In the not-so-distant future, IE won't exist.

Well, Windows 7 and 8.1 will receive support until 2020 and 2023 respectively. That gives us at least four years of IE 11 being the "new IE 6." (Yes, that is a bit of an overstatement, I remember the horrors of IE 6 quite well. It's still disappointing.)


That's definitely what it's supposed to be, and what Microsoft said they were doing.

But Edge updates seem to be a lot rarer than people expected, and seemingly tied more into Windows updates than any sort of regular release schedule.

If Microsoft want to make it a good browser in the long term, they need to move away from tying updates to Windows ones and just release them when new features have been implemented.


In my dream world, everyones on Firefox or Chrome.


Well, that was a long time coming. I was playing with a beta version of CSS Vars 4+ years ago, which was then removed and eventually replaced with this.


I'm not a fan of this...

/* JS */ var styles = getComputedStyle(document.documentElement); var value = String(styles.getPropertyValue('--primary-color')).trim(); // value = 'red'

Rather than calling '--primary-color', you should really be able to call 'color' which points to the variable and will still return red. Otherwise you'll have to know the name of each variable being used, which is much more difficult than knowing the property.


Variables are ultimately used somewhere to set a property, with something like

    color: var(--primary-color);
If care about that property, and not the variable, then get it as usual:

    let value = styles['color']; // 'red'


The point of variables is that you can reuse them, and more importantly changing the variable dynamically changes all of its uses.

So of course you have to know the name of the variables, they're an API for your CSS.


That's exactly what you can do. var() is replaced at computed-value time, so calling gCS().color will return "red" or whatever.

If you use an API that gives you the value at an earlier time, like el.style.color (which is "specified value"), you'll see the var().


Well, you can also get the computed style for 'color'. What ever made you think you couldn't?


Is there a way to access it from javaScript? Can JS code set CSS --color and make it change.


It looks like this can be changed with `setProperty`. There's a demo[1] that works on Firefox 31+ and Chrome 49+

[1] https://www.broken-links.com/2014/08/28/css-variables-updati...


Thanks. I wonder if it could be creatively misused to act as a database.


Yes, it's mentioned in the article.


Why don't they just natively support realtime compilation of SASS/LESS?


the performance would be horrible.


Just add native support for Sass and call it a day.


SASS encourage developers to build long chains of selectors and it makes them brittle and non-reusable.


Yeah, it's easily abused and trivial errors of judgement create non-trivial problems later down the line.

IMO part of the problem is that nested LESS/SASS looks just enough like JSON to mislead inexperienced devs, who often try to treat the nested structure as an object, rather than thinking of it as a string-builder.

It invariably ends up creating huge swarths of pointless specificity and stylesheet bloat.


CSS offers plenty of ways to hang yourself without resorting to SASS. The people who are dangerous with SASS tend to already be just as dangerous with plain CSS, in my experience.

The additional options for self harm are well offset by the features.


"Just add native support for jQuery and call it a day" "Just add native support for React and call it a day"

We can do lots of amazing things in the ecosystem, but often we're working around missing primitives in the platform. Just "adding native support" for today's hottest library doesn't fix things properly. It's better to figure out what problem they were solving, and then fix that problem more directly.

(jQuery is largely solving "DOM APIs suck". We've fixed that a little bit, with things like query() (née querySelector(), which was an awkward first attempt at it) and fetch(), but are still struggling to work through browser dev apathy at things like event registration or creating elements.)

(Figuring out what problem, precisely, React is solving is exciting and interesting. It's non-obvious - it's not just "some DOM things are slow", as there's lots of DOM things both fast and slow, and you don't need a fancy (read:slow) tree-diffing algo to fix those. There's something fundamental going on that we might be able to do better - maybe it's more fully separating the "display thread" that contains DOM from the rest of your JS, and letting you do a lot of DOM-ish manipulation in threads other than the display thread. Maybe that means actually using an even more lightweight display abstraction, so you can cheaply spam out updates without having to do expensive diffing first. There's a lot of possibilities here.)


DOM APIs didn't suck too badly. They weren't great, but they were usable.

The problem was that every old browser had its own API and feature set. Jquery abstracted over all that, including bugs in specific versions of browsers and continually is updated to handle the case of a browser claiming to implement a feature but lying.

Really if all browsers had the same API and feature set, there'd be no need for jQuery as it is today; you'd have a very different library.


Among other problems (perf, etc.) you'd have the application/xhtml+xml problem all over again, this time in styles.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: