About CSS Variables

Please read about the updated syntax of CSS variables in the first and second update of this post.

Since a little bit more than a month (as of the time of writing) there is a Editor’s Draft for a CSS Variables Module by Google (Tab Atkins and Luke Macpherson) and Daniel Glazman. Just a few days ago the Working Draft was updated.
The first draft was written in 2008 by Daniel Glazman but was not added to the official specification. The new WD extends this proposal by Glazman.

Disclaimer: This article is part of a small series about the latest CSS working drafts. The first article in this series was about the CSS Hierarchies Module.

CSS Variables

The CSS Variables Module Level 1 suggests to use variables for data that is reused in stylesheets. These key-value storages provide the possibility to store “meaningless” data as you can do in HTML: Variable keys consist of a data--prefix and the variable name.

Any property name starting with the prefix “data-” is a data property. Data properties are defined to be valid but meaningless as they are meant solely for allowing authors to pass custom data around their page, similar to the custom data attributes in HTML.
Defining Variables With Data Properties – CSS Variables Editor’s Draft

Using data- as a prefix for variables is still in discussion and may likely be changed to something more “connected” to variables ($ or &).

Edit: The mailing-list www-style is discussing the use of data and Ian Muir wrote an article about the problem.

Syntax

Variables are defined by mapping them to the :root pseudo-class. The WD does not really explain why the variables must be declared on the root-element. Maybe it’s because the data needs to be bound to an element to not “fly around” in the global scope (which does not really exist in CSS).
Defined variables can also be set on every other element and overwrite the existing value of a variable.
So this is how you set variables.

To get a specific variable, you do not declare the variable-name but you call data as a function on a certain property with the variables name (without data--prefix) as an argument.

An Example

So here is an example:

/* Set data */
:root {
  data-main-color: #bada55;
}
 
/* Get data */
.foobar {
  color: data(main-color);
}

As said before, variables can be overwritten for specific elements. So we can add the declaration of the variable to .foobar:

.foobar {
  data-main-color: #fe57a1;
  color: data(main-color);
}

The color of .foobar is now #fes7a1 and not #bada55.

Real World Examples

Well, as this is an Editor’s Draft and pretty new it’s not being implemented in any browser.

I’ve created a test case on dabblet with vendor prefixes which tests the two examples above. I’ve run this test on the major browser alphas and nightlies.

Even though variables are not natively supported by CSS in any browser yet, we can use a very similar approach: All CSS preprocessors support variables. Here is an example with SASS:

/* Setting a variable */
$main-color: #bada55;
 
/* Get the variable's value */
.foobar {
  color: $main-color;
}

Conclusion

We can use variables with preprocessors today which is pretty rad. As with the CSS Hierarchies Module CSS in the future may support ideas that come from implementations in preprocessors somehow.
I think most developers are happy about these adoptions and will likely use it. But as it will take some time for all vendors to implement this feature – and even more time until browsers that don’t support such new features vanish – we will have to use preprocessors to get variables in our CSS working.


Update 19.08.2012

Since I wrote the last update the Editors Draft changed: The var()-function changed to use the var-glyph $ as it is known from SASS (described above).

It is now possible to call variables like this:

h1 {
  color: $some-color
}

While it still needs to be defined with the var prefix:

:root {
  var-some-color: #aaa;
}

As Tab Atkins describes in his blog this is going to change back to the old syntax I wrote about in the first place as this causes problems with further implementations of CSS (like variables for selectors and the hierarchy model).


Update 16.04.2012

Since last week the CSS Variables Module Level 1 is an actual Working Draft of the W3C.

It’s now possible to define variables with the var-prefix instead of data which is still pretty complicated. I wonder why they not adept an existing concept as in LESS or SASS.

Thus the data()-function changed accordingly to var().

Furthermore it’s possible to set variables on a certain element but use them in a more complex definition. An example might be the usage as follows (while elements with class important and primary are divs):

.important { var-color: red; }
.primary { var-color: blue; }
div { color: var(color); }

Also nestings for variables are possible:

:root {
  var-color: #ddd;
  var-border: 1px solid var(color);
}

The bright and shiny future

As I think there still are some issues with this Working Draft I like the fast step forward in making this a WD in only a view weeks.
So sooner or later variables will be part of the CSS specification and will be implemented in browsers. I hope this will be very soon.

About The CSS Hierarchies Module Level 3

Since the beginning of February there were some proposals for the CSS3 specification. These proposals are not yet part of the specification and will likely be changed until they get adopted by the CSSWG. One of these drafts is the CSS Hierarchies Module Level 3.

So what’s the Hierarchies Module? And why “Level 3”?

The Hierarchies Module is not exactly new. It exists since the very first steps of CSS and was first released in Dezember 1996 with CSS1. The CSS1 specification is still up, so check it out if you want to.

When you write CSS you always use selectors to target the element you want to style. This works pretty much straight-forward: The right-most simple selector is the one which get the declarations assigned that are defined in the ruleset.
These selectors define a certain hierarchy in your stylesheet.
Note: Please make sure to read Tab Atkins’ Reference for CSS Spec Terms.

An example

Today you would target some links in a navigation like this:

#nav ul li a { color: #000; }

If you’re smart and your markup allows you to do so, you may write:

#nav a { color: #000; }

The li-elements need to be inlined as you want a horizontal navigation:

#nav ul li { display: inline; }

Furthermore the navigation should be aligned on the right and all the links centered:

#nav ul { text-align: right; }
#nav ul li { text-align: center; }

This leaves us with a lot of repetition for the selectors.

#nav ul { text-align: right; }
#nav ul li { text-align: center; display: inline; }
#nav ul li a { color: #000; }

With the Level 3 proposal by Tab Atkins Jr and Shane Stephens (working for Google) this is about to get a little bit easier. The existing system will be extended with some new functionality. This is why it’s called Level 3. (Also it will likely be part of CSS 3 – and not 4 or 10 or something.)

What’s new in there?

Lately you saw the rise of CSS Preprocessors. Everyone has an opinion on this. The thing why so many developers use them is that they help to organize the CSS-code you are writing.
Preprocessors have brought up another idea of CSS hierarchies. And with the CSS Hierarchies Module Level 3 this has been adopted.

The specification draft allows you to nest your rules and use the &-character to reference a parent selector in a certain rule.

Here’s the example from above with the new hierarchy:

#nav ul {
    text-align: right;
    & li {
        text-align: center;
        display: inline;
        & a { color: #000; }
    }
}

As you can see there are no repetitions for the selectors as you can reference them by just writing & and nest them properly.

How can we use this today and when will it be ready for the “real world”?

As you may guess this is not implemented in any browser yet.

As this spec is written by two Google-guys it’s likely that this will be implemented in Chrome in the near future. At the moment this is not working with Chrome 19 (Canary) or WebKit Nightly.
I’ve made this Dabblet to check if the module is supported in a browser or not. caniuse.com does not provide any data for the Hierarchies Module yet.
Aside: Check my Dabblet Chrome App to view all your latest dabblets if you’re a Chrome user.

Tab Atkins proposed another style for nesting. To reference the parent selector you use @this instead of the &-character. Peter Beverloo wrote about this a year ago. Also Tab Atkins has an article about his further plans. This variant was not implement either and is replaced with the new draft for the specification. Anyway you could view the dabblet I’ve made for this propose.

Preprocessors

As mentioned above CSS preprocessors offer the chance to use something like hierarchies in there own way. Here are two examples:

SCSS (aka. SASS)

#nav ul {
    text-align: right;
    li {
        display: inline;
        a {
            color: #000;
            &:hover { color: gray; }
        }
    }
}

Stylus

#nav ul
    text-align right
    li
        display inline
        a
            color #000
            &:hover
                color grey

As you can see there is a difference in how preprocessors treat the &-character as a reference: In the CSS specification draft & is obligatory in every nested rule you write to reference the parent selector. Preprocessors need them only if there is a pseudo-class or -element or a combinator (such as ~ or >) used for a specific selector.

As I stated in the introduction it may happen that the specification will be changed until it becomes final or is adopted by the CSS Working Group. I recommend you follow the discussions about this topic in order to stay up to date.
When this specification will be implemented by one of the browser vendors it’s just a matter of weeks until it will be adopted by the others I guess.

But, as the draft states, this is not yet part of CSS:

This document is purely an Editor’s Draft. It has not yet been adopted by the Working Group, and should not be considered to be part of CSS.

~ CSS Hierarchies Module – Status

Opinion

Personally I hope that referencing the parent selector with & will not be in the final specification as it is now. It’s not needed as the rules are nested anyway and preprocessors nowadays treat them better.

Anyway the new nesting is pretty useful as it reduces the redundancy of writing selectors in CSS. In connection with other upcoming specifications like the CSS Variables Module Level 1 this is what is needed and will be helpful for every web-developer once it will be implemented in browsers.

Dabblet Chrome App

Dabblet Chrome App

I think all of you know Lea Verou’s dabblet.

dabblet is an interactive playground for quickly testing snippets of CSS and HTML code. It uses -prefix-free, so that you won’t have to add any prefixes in your CSS code. You can save your work in Github gists, embed it in other websites and share it with others.
About dabblet

Some time ago I made this tiny Google Chrome App for jsFiddle which is in case just a bookmarklet with a bigger icon.

I did this for dabblet, too but extended the app to something more: It displays all your dabblets with title and creation-date. You can then visit your dabblet directly.

You can find the app in the Google Chrome App store now.

Download

This project is on GitHub, so please feel free to contribute and report bugs and feature requests.

Changelog

These are the major changes. All commits can be found on GitHub.

v1.0.0 – Aug. 19, 2012

  • Add button for viewing gist
  • Remove hogan.js in favor of an own replacer
  • Show “view dabblet” link in GitHub newsfeed

v0.7 – Feb. 13, 2012

  • Add search – #2
  • Rewrite code-basis based on JS AMD with RequireJS
  • Display message if user has no gists to display – #3

v0.45 – Feb. 02, 2012

About Git’s Cherry-Picking

At /gebrüderheitz we use Git as a version control system as we think this is the best to work together on a level which is easy to learn and work with.

Before we used Git we’ve used SVN but this is by far not as flexible as Git. There are enough posts gathering the difference between Git and SVN so I will not cover any of these.

When working in a team it’s important to keep your different stages of development in sync and control somehow: There is a front-end development going on which is in deep connection with the server-side development; you may also want to develop a new sub-project within your main project; and then there is a tested and fully working live-version of a project.

With Git it’s pretty obvious to use branches to organize different states of the project’s development.

Branches

Branches can consist of the whole project’s files and some more commits covering a specific issue or feature. Also they can show a whole different approach of a project and do not necessarily need to consist of the main project’s files.

For our projects we try to keep these branches tight so we will not have a problem when it comes to merging branches – to let one feature or development approach flow into the main development line. Keep in mind that branches in a project are indeed cheap. So use them where you think they might fit. Don’t think about it to long. It will help you in your whole working-process.

Cherry-Picks

Sometimes, when it comes to bug fixing you don’t want to put fixes in your live-branch. You fix them in your development-branch and commit them over there. The dev-branch might be on a whole other level as your live branch as you’ve developed some things that will be part of a next major update or so. Therefore Git’s cherry-picking has become a perfect addition to our workflow.

With cherry-picking you are able to pull single commits from one branch to another.

Another part where you might want to use cherry-picking is when a colleague and you develop in two different branches and one contributes to the other’s sub-project without changing the branch. There are some other use cases. Please feel free to share where you use cherry-picking through the comments.

How to Use Cherry-Picking

I am using a GUI for doing all the Git-related stuff which is pretty handy and easy. But I think it is important to know how to handle Git via the console anyway.

Here is how to cherry-pick commits.

At first you need to commit your changes in the development branch.

$ git commit -m 'This is some bugfix-message'

You now need the commit-hash for the commit you want to cherry-pick in another branch.

$ git log -1

This will return the meta-data for your latest commit. You can now copy the first 7 or so numbers of the commit-hash. It’s not necessary to copy the whole hash as the hash-partial only needs to be unique above all commits of the project.

Now you need to change your checked out branch to the branch where you want to insert – cherry-pick – this particular commit. While <live> is the name of this branch, do this:

$ git checkout <live>

Keep in mind to commit all your changes in the current branch first or stash them.

Lastly you have to tell the checked out branch to use this commit and do the cherry-pick for real!

$ git cherry-pick <hash-partial>

<hash-partial> is pretty self explaining I guess.

Git now automatically merges the commit into the specific branch.

Merging Branches Later

From what I experienced it is no problem to merge branches later when you cherry-picked some commits. This works just fine!

Is Mothereffin’ jQuery Up?

Some weeks ago I made a pull request for HTML5Boilerplate which should update jQuery to the latest version available on the Google CDN. How ever I copied the old version of minified jQuery because the uncompressed version was available but the minified wasn’t. Stupid thing!

That’s why I created Is Mothereffin’ jQuery up? The service checks three major CDNs for the availability of the latest jQuery version.

View Is Mothereffin’ jQuery up?

How to Check if the File is up

I had some difficulties to find the right method how to detect if a file is already available with JavaScript. If you don’t have to deal with cross-domain requests this is not a big thing and done pretty easy. But I need cross-domain requests.

If a file is not available on a server, the request dies with an error 404 and no callback will be called. See this Fiddle for a test-case. Even a try-catch-expression does not help.

I decided to check all files for availability and if the request ends up in an error nothing will happen. The script will check if all files are available after three seconds and will otherwise “tell” the user that it’s not. This is not a bullet-proof method as it could take more then three seconds to request all files. If you have a better idea please let me know.
For the moment the resources will be labeled as “available” when they are loaded even if they were labeled “not available” before. So you will not end up with wrong result, it just may take a second more to show you that.

The Styles

The project was build “mobile-first”. It makes use of the CSS3 Flexible Box Model instead of float and all the other stuff.

I’m not supporting IE in any way because I think most web-developer don’t use Internet Explorer.

Todo

  • Support more libraries such as Mootools, Dojo, Prototype, ExtJS and YUI
  • Let users submit other CDN via a form
  • Link buttons to their libraryDone with this commitsuggestion by Mathias

Let me know if you want some other features.

Contribute via GitHub

I’ve put this project up on GutHub. Feel free to contribute or just watch it.

Feature requests can also be placed in the issue-tracker there.

Responsive Media

There is a big discussion going on at the moment covering the actual point of how to deal with images and media et al. on mobile-phones and other devices as there are some things that don’t work as on a desktop computer:

  • Bandwidth
  • Screen size
  • Performance / Velocity

The question is how to deliver responsive images on a mobile website.

You maybe use something like img { max-width: 100%; height: auto; } in your responsive design to prevent images from being bigger then the screen of a mobile device.

In most of the cases this shrinks images in its displayed size, which is a processor intensive thing to do – especially when you are on a mobile device and don’t have endless processor capacity this hurts.
The shrinking itself does not change the file-size that has to be loaded; it remains the same as on a desktop for example. As bandwidth is the bottleneck these days if you are on a mobile device, this is the issue where people want to see some improvement.

What can we do about it?

There are a couple of proposals and known techniques on how to solve the problem:

1. Resize images with PHP

This is something you could only do if you know the screen-size before you load the images them self. So you have to inject HTML through JavaScript for example and change the sources for images accordingly.

The Adaptive Images framework a similar technique. Check out the source on GitHub.

2. Request different images using data-attributes

An article by Nicolas Gallagher covers this method using CSS to detect which source would be best to use.

The method could work like this: You have an image which has a really small file size and is served for every device at first (mobile first approche).

<img src="image.jpg" alt="" data-src-600px="image-600px.jpg" />

Now you are going to change the file if the screen is bigger by using the content-property of CSS and its attr() function.

@media (min-device-width:600px) {
    img[data-src-600px] {
        content: attr(data-src-600px, url);
    }
}

Please have a look at the article for detailed information.

An idea that goes beyond the replacement of images with the attr()-function is the usage of content: url(myimage.jpg) replaced;. This is something suggested by Tab Atkins Jr. on the W3C www-styles mailing list – called replaced content.
Something about replaced content appears in the CSS-spec but it does not look to be exactly what Tab is referring to.

3. Introduce new attributes to the <img>-tag

Anselm Hannemann shares the idea of introducing a media-attribute that has some sort of “sizing-parameter”. It is supposed to be combined with the media-src-attribute which also has the sizing-parameter.
The HTML could look something like this:

<img src="myimage_xs.jpg"
media-xs="(min-device-width:320px and max-device-width:640px)" media-src-xs="myimage_xs.jpg"
media-m="(min-device-width:640px and max-device-width:1024px)" media-src-m="myimage_m.jpg"
media-xl="(min-device-width:1024px)" media-src-xl="myimage_xsl.jpg">

As you can see the media-attributes contain media-queries which describe when to take a certain image-source.

4. Using JavaScript

There are some ideas on how to deal with this topic using JavaScript.

The FilamentGroup for example published its “Responsive Images”-project on GitHub. They are using “Mobile-First” to present a small-sized image on every device and replace this with JavaScript on window load.
You can find out more about how it works on their blog. They also published a demo.

Peter-Paul Koch presented a possible way on how to combine media queries with JavaScript. Which is not really new I think but a good summery.

Another approach could be a new attribute for the script-tag: Scott Jehl suggested to call it preparse. The script could then be used to replace sources in HTML fitting the current client-need.

5. A new image-format containing different sizes

People aso had the idea of creating an own image-format which contains for example four layers with different image sizes. The image then “decides” which format to take and serves this to the client without its three sibling-layers.

At the moment there is a format called MrSID developed by LizardTech which can have one or more compression rates.

Another approach is the JPEG 2000 file-format. It can carry out different optimization-levels for images. Read more about it on the Wikipedia-page I linked above.

Media? But this was only about images…

Yup, right! Images are just one aspect when it comes to responsive media.
Videos for example are another thing. YouTube offers different video-sizes for watching. You have to choose manually which one to use. A possibility to select this resource automatically, build into the browser would be awesome!

JPEG 2000 has a video-equivalent developed by the same group of people as the JPEG-format called Motion JPEG 2000. Find more information about this here.

Conclusion

As it turns out many developers are not aware of the problems that come up with a real responsive design – even HTML5-specification writer are calling it “a niche problem”. This is why it is hard to develop a specification for a native API as for example Anselm Hannemann suggests.

But maybe the decision which technique might be best for solving the problem of serving responsive media has to be finished first before anything is spec’d up.

Moar!

Some more resources where the topic is discussed:

Thanks!

Thanks goes out to Anselm, for reading what I wrote and helping me with some further information.

A Travel Through Time – and Back

Somehow… <time> Disappeared

As you might have heard the <time>-element was removed from the HTML5 specification last saturday by Ian “Hixie” Hickson, the editor of the spec. Hixie decided to remove <time> and replace it by the more general <data>-element.

A question that came up: Why got<time> removed and why did nobody stop Hixie?

Well: There Google+. Also we talked about this issue on the (german) podcast Working Draft on monday. I was invited by Christian “Schepp” Schäfer to discuss about some stuff with himself and Marc.

Steve Faulkner was the first one (for what I noticed) that tweeted about that intensively and was really upset by the dropping. Furthermore it was his tweet that encouraged me to keep track of the whole story.

Steve explained on the the mailing-list of the W3C why he likes to revert the changes made by Hixie the day before. Others also liked the time-element and requested a revert.

There were some pretty good blog posts about that topic, as for instance

As it turns out <time> is wildly in use all over the web:

  • the WordPress twentyeleven-theme uses it
  • The Boston Globe makes use of it
  • I’m using it on this page
  • And many others too…

As so many people where effected by the change that was made to the spec and many people though it was a bad decision there was hope that this story was not over yet… And it wasn’t.

Again Steve Faulkner tweeted:

“I feel confident that <time> will be back in the W3C HTML5 specification by the end of the week”

~ Steve Faulkner, 31. Oct 2011 via Twitter

This was a decent statement as you can say by today.
There were proposals on how to deal with <time> and how to improve it for the future and get it back into the spec. A leading role in this process is held by Tantek Çelik. Read his comment on Bruce Lawson’s post. Also Stephanie Sullivan Rewis has some interesting thoughts.

And then – the Turningpoint

Currently the TPAC 2011 is happening which is a conference and meeting of the W3C and its members.
At (Please notice my use of <time> in this case. Nice, right… right?) people of the W3C HTML Working Group met and discussed about <time> and its removal. You could have followed the discussion on IRC on W3C’s channel #html-wg. Here you can find the “minutes” (a transcription) of it. Tantek added this as a point for discussion to the Agenda.

As this all was said, there was a mail on the mailing-list by the Chairs of the HTML WG asking the editor of the spec (Hixie) “for a revert of this change to be completed no later than the end of day on Tuesday 8th of November”. If Hixie will not change this until Tuesday the Chairs will ask the W3C staff “to make this change”. What ever this means then… I have no idea.

Today Tantek began to define some new requirements for the <time>-element and its attribute datetime (especially the syntax of the mentioned attribute).

So what’s the conclusion now?

All the things I mentioned above show how strong the community is and how many people try to get the best out of the tools we have.

Hixie’s decision to remove the <time>-element in favor of the <data>-element was not found democratically by everyone contributing to the HTML5 spec but was a bossy behavior.

Personally I learnd a lot about the process within the W3C, the WHATWG, how the specification is build, and so on asf… This was pretty good and I feel good about how things work.

I hope there are more people who like keep a little bit more track of what is going on with all the new stuff and be part of decisions that are made.

Thank you for reading all the words I wrote.

Thank you Steve, Tantek, thank you Eric Eggers, Shelley Powers, thank you everyone who was able to do something about the odd removal of <time>. You guys rockkk!

Lea Verou’s Animatable

Lea Verou publishes some really great stuff. Her latest work is Animatable. A tool to showcase the variety of things you can do with CSS3 animations. And it’s awesome.

Some weeks ago I had this article about rotating images like I use in the footer of this page. There is an animation in Lea’s demos that makes use of the same properties.

You will find some nice cutting edge CSS3-techniques in the demos so make sure to check out the source-code on GitHub. You can also contribute and check in a pull request if you want to.

Edit: And by the way… Lea writes about her idea :)

How to Build an Accordion-Menu using CSS and a bit of jQuery

We’re doing a project these days where we use an accordion-menu to show some content.
I want to share with you how I did this using jQuery and CSS. This is pretty easy and I want to encourage you not to use any plugin or so but to write the code yourself and learn a bit more about how to use CSS and jQuery and save some microseconds on your loading type.

The HTML

This is kinda straightforward I think. We don’t need a wrapper for the accordion-menu. Check it:

<section id="experts" class="accordion-item">
  <h1><a href="#experts">Experts</a></h1>
  <div class="content"></div>
</section>

This is how every item for your accordion should look like.

The CSS-Part

Some basic CSS-rules for the header and the content of each item.

.accordion-item h1 a { display: block; font-size: 1.5em; text-align: center; }
.accordion-item .content { display: none; }

You may want to do at least a bit more on the styles but that’s up to everybody on its own.

We want to keep this accordion accessible for people who don’t use JavaScript, what is kinda unusual these days I think… but you never know!
That’s why we added an id to each accordion-item and link to this section in the headline through #experts for instance. We can now show the content of the requested id with CSS:

:target .content { display: block; }

So we’re all set up with the accordion. We can now add some effects with JavaScript.

Using jQuery

First, we will add a line that will show the content of the first element on load:

$('.accordion-item').eq(0).addClass('current').find('.content').show();

And than the we will listen to clicks on the headlines and do some actions afterwards. Read the comments in this snipped.

// Listen to click on headline-link
$('.accordion-item h1 a').click(function(e) {
  // prevent auto scrolling to id
  e.preventDefault();
 
  // Register the variables for better performance
  var $parent = $(this).closest('.accordion-item'),
      $content = $parent.find('.content');
 
  // If the clicked section is not the active one
  if (!$parent.hasClass('current')) {
 
    // SlideUp "old" and remove class
    $('.accordion-item.current .content').slideUp()
      .parent().removeClass('current');
 
    // Add class and slide down content
    $parent.addClass('current');
    $content.slideDown();
 
  // If the click was triggered on the currently active section
  // remove the class and slide up content
  } else {
    $parent.removeClass('current');
    $content.slideUp();
  }
});

And this is it I guess. Working pretty much in every available browser. The CSS :target pseudo-class is not available in every browser though, as it is a CSS3-pseudo-class. And now guess which browser this might be… Right Internet Explorer. It is supported with version 9 but not before.
You will find more information about :target in the spec. Check out the Can I Use table on CSS3-Selectors.

Download the files

I’ve made a demo of this on jsFiddle. Play around a little bit or download the files, if you want to.
Demo     Download