Zen Coding

Zen Coding is a plugin for HTML, XML, XSL, CSS fast code editing which could be used in different text editing software and/or IDEs. Recently, through the Web Essentials VS Extension, Zen coding is also available in Visual Studio. This functionality is activated by pressing TAB key right after you write the zen code.

Zen coding has a specific syntax, and the code is created by combining html tags and ‘zen code operators’. These operators include :

Operator Operation
# Create ID attribute
> Child element
. CSS style
* Mutiplication of elements
[] Custom attribute
+ Sibling element
^ Climbs one hierarchy level up

Let’s demonstrate these by examples.

Specifying the ID

If we want to create a div element which has an id named container, then we would write

div#container and when we press TAB, and the result will be <div id="container"></div>

Creating child elements

If we want to create nested elements, then we would use greater then (>) symbol to specify nested elements. Writing ul>li produces

<ul>
<li></li>
</ul>

with proper indentation.

Adding CSS class to element(s)

The dot symbol will add css class to an element. Modifying the last example code to ul#menu>li.menuItem will produce

<ul id="menu">
<li class="menuItem"></li>
</ul>

Creating many elements

If we want to create more than one element of the same type, then we will use multiplier (*) operator. If we write ul#menu>li.menuItem*5 the result will be

<ul id="menu">
<li class="menuItem"></li>
<li class="menuItem"></li>
<li class="menuItem"></li>
<li class="menuItem"></li>
<li class="menuItem"></li>
</ul>

Creating custom attributes

In some cases, there is a need for custom attributes (e.g. new html data-dash attributes). Let us modify our last example so it includes a data-value attribute. If we write ul#menu>li[data-value].menuItem*5 and press TAB, the result will be


<ul id="menu">
<li data-value="" class="menuItem"></li>
<li data-value="" class="menuItem"></li>
<li data-value="" class="menuItem"></li>
<li data-value="" class="menuItem"></li>
<li data-value="" class="menuItem"></li>
</ul>

We can even give a default value to the attribute by changing attribute section to [data-value=val].

Creating sibling elements

Let us create a div for search with an id equal to ‘search’ and two input elements inside, one textbox and one search button. Our zen code would look like this:

div#search>input[type=text]+input[type=submit,value=search]

and it will produce

<div id="search">
<input type="text" value="" />
<input type="submit" value="search" />
</div>

Level up

The caret operator (^) enables us to go one level up in hierarchy. E.g.

CodeĀ div#container>div#element1^div#element2 will produce this HTML

<div id="container">
<div id="element1"></div>
</div>
<div id="element2"></div>

This is it folks. I hope you like it.

Leave A Comment

Your email address will not be published. Required fields are marked *