About The Author

Sergey Chikuyonok is a Russian front-end web-developer and writer with a big passion on optimization: from images and JavaScript effects to working process and … More about Sergey

Zen Coding: A Speedy Way To Write HTML/CSS Code

Quick Summary

In this post we present a new speedy way of writing HTML code using CSS-like selector syntax — a handy set of tools for high-speed HTML and CSS coding. It was developed by our author Sergey Chikuyonok and released for Smashing Magazine and its readers.

Table of Contents
Membership counter

Members support Smashing

Wonderful, friendly people who keep this lil' site alive — and get smarter every day.

Are you smashing, too? →

In this post we present a new speedy way of writing HTML code using CSS-like selector syntax — a handy set of tools for high-speed HTML and CSS coding. It was developed by our author Sergey Chikuyonok and released for Smashing Magazine and its readers.

How much time do you spend writing HTML code: all of those tags, attributes, quotes, braces, etc. You have it easier if your editor of choice has code-completion capabilities, but you still do a lot of typing.

You may want to take a look at the following related posts:

We had the same problem in JavaScript world when we wanted to access a specific element on a Web page. We had to write a lot of code, which became really hard to support and reuse. And then JavaScript frameworks came along, which introduced CSS selector engines. Now, you can use simple CSS expressions to access DOM elements, which is pretty cool.

But what if you could use CSS selectors not just to style and access elements, but to generate code? For example, what if you could write this…

div#content>h1+p

…and see this as the output?

<div id="content">
<h1></h1>
<p></p>
</div>

Today, we’ll introduce you to Zen Coding, a set of tools for high-speed HTML and CSS coding. Originally proposed by Vadim Makeev (article in Russian) back in April 2009, it has been developed by yours truly (i.e. me) for the last few months and has finally reached a mature state. Zen Coding consists of two core components: an abbreviation expander (abbreviations are CSS-like selectors) and context-independent HTML-pair tag matcher. Watch this demo video to see what they can do for you.

If you’d like to skip the detailed instructions and usage guide, please take a look at the demo and download your plugin right away:

Demo

  • Demo (use Ctrl + , to expand an abbreviation, requires JavaScript)

Downloads (Full Support)

Downloads (Partial Support, “Expand Abbreviation” Only)

Now, let’s see how these tools work.

Expand Abbreviation

The Expand Abbreviation function transforms CSS-like selectors into XHTML code. The term “abbreviation” might be a little confusing. Why not just call it a “CSS selector”? Well, the first reason is semantic: “selector” means to select something, but here we’re actually generating something, writing a shorter representation of longer code. Secondly, it supports only a small subset of real CSS selector syntax, in addition to introducing some new operators.

Here is a list of supported properties and operators:

  • E Element name (div, p);
  • E#id Element with identifier (div#content, p#intro, span#error);
  • E.class Element with classes (div.header, p.error.critial). You can combine classes and IDs, too: div#content.column.width;
  • E>N Child element (div>p, div#footer>p>span);
  • E+N Sibling element (h1+p, div#header+div#content+div#footer);
  • E*N Element multiplication (ul#nav>li*5>a);
  • E$*N Item numbering (ul#nav>li.item-$*5);

As you can see, you already know how to use Zen Coding: just write a simple CSS-like selector (oh, “abbreviation”—sorry), like so…

div#header>img.logo+ul#nav>li*4>a

…and then call the Expand Abbreviation action.

There are two custom operators: element multiplication and item numbering. If you want to generate, for example, five <li> elements, you would simply write li*5. It would repeat all descendant elements as well. If you wanted four <li> elements, with an <a> in each, you would simply write li*4>a, which would generate the following output:

<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>

The last one–item numbering is used when you want to mark a repeated element with its index. Suppose you want to generate three <div> elements with item1, item2 and item3 classes. You would write this abbreviation, div.item$*3:

<div class="item1"></div>
<div class="item2"></div>
<div class="item3"></div>

Just add a dollar sign wherever in the class or ID property that you want the index to appear, and as many an you want. So, this…

div#i$-test.class$$$*5

would be transformed into:

<div id="i1-test" class="class111"></div>
<div id="i2-test" class="class222"></div>
<div id="i3-test" class="class333"></div>
<div id="i4-test" class="class444"></div>
<div id="i5-test" class="class555"></div>

You’ll see that when you write the a abbreviation, the output is <a href=“”></a>. Or, if you write img, the output is <img src=“” alt=“” />.

How does Zen Coding know when it should add default attributes to the generated tag or skip the closing tag? A special file, called zen_settings.js describes the outputted elements. It’s a simple JSON file that describes the abbreviations for each language (yes, you can define abbreviations for different syntaxes, such as HTML, XSL, CSS, etc.). The common language abbreviations definition looks like this:

'html': {
'snippets': {
'cc:ie6': '<!--[if lte IE 6]>nt${child}|n<![endif]-->',
...
}, 

'abbreviations': {
'a': '<a href=""></a>',
'img': '<img src="" alt="" />',
...
}
}

Element Types

Zen Coding has two major element types: “snippets” and “abbreviations.” Snippets are arbitrary code fragments, while abbreviations are tag definitions. With snippets, you can write anything you want, and it will be outputted as is; but you have to manually format it (using n and t for new lines and indentation) and put the ${child} variable where you want to output the child elements, like so: cc:ie6>style. If you don’t include the ${child} variable, the child elements are outputted after the snippet.

With abbreviations, you have to write tag definitions, and the syntax is very important. Normally, you have to write a simple tag with all default attributes in it, like so: <a href=“”></a>. When Zen Coding is loaded, it parses a tag definition into a special object that describes the tag’s name, attributes (including their order) and whether the tag is empty. So, if you wrote <img src=“” alt=“” />, you would be telling Zen Coding that this tag must be empty, and the “Expand Abbreviation” action would apply special rules to it before outputting.

For both snippets and abbreviations, you can ad a pipe character (|), which tells Zen Coding where it should place the cursor when the abbreviation is expanded. By default, Zen Coding puts the cursor between quotes in empty attributes and between the opening and closing tag.

Example

So, here’s what happens when you write an abbreviation and call the “Expand Abbreviation” action. First, it splits a whole abbreviation into separate elements: so, div>a would be split into div and a elements, with their relationship preserved. Then, for each element, the parser looks for a definition inside the snippets and then inside the abbreviations. If it doesn’t find one, it uses the element’s name as the name for the new tag, applying ID and class attributes to it. For example, if you write mytag#example, and the parser cannot find the mytag definition among the snippets or abbreviation, it will output <mytag id=“example”><mytag>.

We have made a lot of default CSS and HTML abbreviations and snippets. You may find that learning them increases your productivity with Zen Coding.

HTML Pair Matcher

Another very common task for the HTML coder is to find the tag pair of an element (also known as “balancing”). Let’s say you want to select the entire <div id=“content”> tag and move it elsewhere or just delete it. Or perhaps you’re looking at a closing tag and want to known which opening tag it belongs to.

Unfortunately, many modern development tools lack support for this feature. So, I decided to write my own tag matcher as part of Zen Coding. It is still in beta and has some issues, but it works quite well and is fast. Instead of scanning the full document (as regular HTML pair matchers do), it finds the relevant tag from the cursor’s current position. This makes it very fast and context-independent: it works even with this JavaScript code snippet:

var table = '<table>';
for (var i = 0; i < 3; i++) {
table += '<tr>';
for (var j = 0; j < 5; j++) {
table += '<td>' + j + '</td>';
}
table += '</tr>';
}
table += '</table>';

Wrapping With Abbreviation

This is a really cool feature that combines the power of the abbreviation expander with the pair tag matcher. How many times have you found that you have to add a wrapping element to fix a browser bug? Or perhaps you have had to add decoration, such as a background image or border, to a block’s content? You have to write the opening tag, temporarily break your code, find the appropriate spot and then close the tag. Here’s where “Wrap with Abbreviation” helps.

This function is pretty simple: it asks you to enter the abbreviation, then it performs the regular “Expand Abbreviation” action and puts your desired text inside the last element of your abbreviation. If you haven’t selected any text, it fires up the pair matcher and use the result. It also makes sense of where your cursor is: inside the tag’s content or within the opening and closing tag. Depending on where it is, it wraps the tag’s content or the tag itself.

Abbreviation wrapping introduces a special abbreviation syntax for wrapping individual lines. Simply skip the number after the multiplication operator, like so: ul#nav>li*>a. When Zen Coding finds an element with an undefined multiplication number, it uses it as a repeating element: it is outputted as many times as there are lines in your selection, putting the content of each line inside the deepest child of the repeating element.

If you’ll wrap this abbreviation div#header>ul#navigation>li.item$*>a>span around this text…

About Us
Products
News
Blog
Contact Up

You’ll get the following result:

<div id="header">
<ul id="navigation">
<li class="item1"><a href=""><span>About Us</span></a></li>
<li class="item2"><a href=""><span>Products</span></a></li>
<li class="item3"><a href=""><span>News</span></a></li>
<li class="item4"><a href=""><span>Blog</span></a></li>
<li class="item5"><a href=""><span>Contact Up</span></a></li>
</ul>
</div>

You can see that Zen Coding is quite a powerful text-processing tool.


Key Bindings

  • Ctrl+, Expand Abbreviation
  • Ctrl+M Match Pair
  • Ctrl+H Wrap with Abbreviation
  • Shift+Ctrl+M Merge Lines
  • Ctrl+Shift+? Previous Edit Point
  • Ctrl+Shift+? Next Edit Point
  • Ctrl+Shift+? Go to Matching Pair

Online Demo

You’ve learned a lot about how Zen Coding works and how it can make your coding easier. Why not try it yourself now, right here? Because Zen Coding is written in pure JavaScript and ported to Python, it can even work inside the browser, which makes it a prime candidate for including in a CMS.

  • Demo (use Ctrl + , to expand an abbreviation, requires JavaScript)

Supported Editors

Zen Coding doesn’t depend on any particular editor. It’s a stand-alone component that works with text only: it takes text, does something to it and then returns new text (or indexes, for tag matching). Zen Coding is written in JavaScript and Python, so it can run on virtually any platform out of the box. On Windows, you can run the JavaScript version of Windows Scripting Host. And modern Macs and Linux distributions are bundled with Python.

To make your editor support Zen Coding, you need to write a special plug-in that can transfer data between your editor and Zen Coding. The problem is that an editor may not have full Zen Coding support because of its plug-in system. For example, TextMate easily supports the “Expand Abbreviation” action by replacing the current line with the script output, but it can’t handle pair-tag matching because there’s no standard way to ask TextMate to select something.

Full Support

Partial Support (“Expand Abbreviation” Only)

Aptana is my primary development environment, and it uses a JavaScript version of Zen Coding. It also contains many more tools that I use for routine work. Every new version of Zen Coding will be available for Aptana first, then ported to Python and made available to other editors.

The Coda and Espresso plug-ins are powered by the excellent Text Editor Actions (TEA) platform, developed by Ian Beck. The original source code is available at GitHub, but I made my own fork to integrate Zen Coding’s features.

Conclusion

Many people who have tried Zen Coding have said that it has changed their way of creating Web pages. There’s still a lot of work to do, many editors to support and much documentation to write. Feel free to browse the existing documentation and source code to find answers to your questions. Hope you enjoy Zen Coding!

Smashing Editorial (al)