jQuery: detecting validation messages in Ajax

Ajax responses are usually very simple to handle. Generally speaking, all you have to do is inserting the content of the response into the DOM. But sometimes they can be quite complex. Suppose that you have to perform a form validation with Ajax. The served-side language can either return a list of validation errors or a message indicating that the user has sent the form successfully. How can you choose between these two types of messages?

I found a simple solution: for validation errors, I wrap the message inside the following HTML element.

<div class="error" rel="label"></div>

As you can see, I use the CSS class error as an internal flag. Instead, the rel attribute has a value that corresponds to the ID of the form field that needs to be highlighted. In my particular case, I've chosen to highlight its corresponding label element instead. On the contrary, the wrapper for successful responses is much simpler:

<div class="success"></div>

However, there's a catch: I usually serve my responses as text/plain, since they're considerably faster to load. What I really need is a function that parses error messages and another that inserts the message into the DOM. Here they are:

var parseValidationErrors = function(html) {
       var errorList = $('<div class="error-list"></div>');
       var lines = html.split('\n');
       var attributes = [];
       for(var i=0; i<lines.length; i++) {
           var line = lines[i];
    var attrRe = /rel=".+"/;
    if(attrRe.test(line)) {
        var match = line.match(attrRe);
        var rawAttr = match[0];
        var attr = rawAttr.replace('rel="', '').replace('"', '');
       for(var j=0; j<attributes.length; j++) {
           var rel = attributes[j];
    var id = '#' + rel;
    var parseSuccessMessage = function(target, html) {

parseValidationErrors() uses regular expressions to find and extract the value of the rel attribute from the Ajax response, whereas parseSuccessMessage() simply replace an existing portion of the DOM with the Ajax content. Now we need a third function that is actually able to detect the type of message returned and act accordingly:

var detectResponseType = function(html) {
    var errorClass = /class="error"/;
 if(errorClass.test(html)) {
     return false;
 } else {
     return true;

This function only tests whether the message returned contains the CSS class error. Now we can put it all together:

$('#testForm').submit(function(e) {
     var data = 'test=foo&bar=baz';
       type: 'POST',
       url: 'ajax.php',
       data: data,
       success: function(html) {
  if(detectResponseType(html)) {
      parseSuccessMessage('#test', html);
  } else {

jQuery: getting form data for Ajax

One of the most requested features when using Ajax with jQuery is something that can be used to prepare a serialized string to be passed to the $.ajax() method. Many plugins that deal with forms provide this feature, though not all of these plugins serialize data in the same way. So I've created the following jQuery plugin that serializes form data and turns it into a string:

(function($)) {

    $.fn.getFormData = function() {
       var data = [];
       this.find(':input').not(':submit').each(function() {
         var $inputName = $(this).attr('name');
         var $inputVal = $(this).val();
         var formValue = $inputName + '=' + $inputVal;
      return data.join('&');



$('#myForm').submit(function(e) {

    var data = $(this).getFormData();
        type: 'POST',
        url: 'ajax.php',
        data: data,
        success: function(html) {


The getFormData() method collects all the values of the input and textarea elements, but it doesn't take into account the submit button of a form. It can be used in a variety of contexts and it's really lightweight.

jQuery and Prototype: differences

Although I eventually switched to jQuery almost a year ago, I've been using also Prototype for a very long time. During this period, I noticed some differences between jQuery and Prototype that I'd like to share here. First, Prototype is a JavaScript framework, whereas jQuery is actually a JavaScript library. A framework is something more related to a certain level of abstraction and actually more suitable for very complex applications than a library. On the other hand, a library is certainly a tool that turns out to be very useful for practical scenarios, such as leveling the differences between browser implementations, adding effects, handling events and so on.

In that vein, jQuery is more user-friendly than Prototype. As its motto says ("Do more with less"), jQuery wants explicitly make the life easier for web developers. Instead, Prototype wants to create an ideal background to build up complex web applications. If you notice, jQuery has the concept of plugins, but not Prototype, because the library in itself cannot provide all the features needed. Second, if we look at both libraries from an OOP perspective, jQuery uses this approach behind the scenes, actually wrapping everything inside a global namespace (the alias $), thus creating a selector chain.

On the contrary, Prototype uses an interface-based approach, so that you can either choose to use its custom methods or the DOM core methods. For example:

var divs = $('test').getElementsByTagName('div');

As you can see, the $ alias is not a wrapper but only a method to reference an element. In fact, you can actually attach a DOM core method to it. Instead, in jQuery you can do it in two ways:

var divs = $('#test div').get();
var divs = $('#test')[0].getElementsByTagName('div');

This happens because in jQuery everything is bound to a chain, so you have to move your code outside that chain. Another example concerns the handling of effects. Prototype uses interfaces, so you have something like Element.hide(element), whereas in jQuery you can write $(element).hide().

To summarize: both jQuery and Prototype are really powerful tools, but they're different in concept and design.

How to Get a Microsoft Excel Look With HTML/CSS Tables

This is a guest post by Yoav Ezer.

Occasionally we will want to present our Excel spreadsheet data in a web page and find the options lacking. If you have ever exported a Microsoft Office document you will know the garbage formatting instructions that get sent along with the information. How can we preserve the Excel look without the Office markup? You are in luck, we have a solution!

With a little bit of CSS magic we can in fact replicate the major Excel versions look and feel quite realistically in your plain ol' HTML tables. Not only that, but the Cogniview code magicians have given you a choice of which version of Excel you would like to emulate.

Go here to download a zip file containing the example web page (shown below) and the CSS files. There is one style sheet for each version of Excel, plus a couple of images to give the special 2007 fancy graduated shading bits.

When you open up the zip file and launch the web page, you will see we have grabbed some example data from InfoPlease.com representing the US City populations. At the top of the page is a drop-down list allowing you to select the look and feel you want to display. This drop-down changes the CSS for the shown table.

To use the CSS stylings in your own projects, first you must tell your web page which style sheet you wish to use:

<link rel="stylesheet" type="text/css" href="excel-2007.css" />

Next, in your table, give the class that you want to use:

<table class="ExcelTable2007">

In the above examples I have used 2007, just change those to the version you would like.

Use the TH tag for the first row of your table ("table header") and set the 'heading' class for the first column. For example:

<tr<th class="heading"> </th<th>A</th><th>B</th><th>C</th></tr>
<tr<td class="heading">2</td><td>some data</td></tr>

There we have it, a Microsoft Excel look in our web pages!

Obviously there is one major limitation of this exercise... people might think they can interact with your faux spreadsheet as if they were using Excel and be disappointed. Not much we can do about that without a whole new project, but at least this beats doing a bunch of screenshots or using the horrible Office export tools.

About the author

Yoav Ezer co-authors the technology and productivity blog Codswallop. He is also the CEO of a company that produces PDF to XLS conversion software.

For more Excel tips from Yoav, join him on Facebook or Twitter

Implementing the MVC pattern with PHP and Ajax

Stoyan Stefanov, one of the leading JavaScript developers at Yahoo!, wrote this interesting article about the implementation of the MVC design pattern with PHP and Ajax. This article confirmed the fact that Ajax requests should be always treated sequentially. In fact, an Ajax action always takes place after a specific HTTP request. For example, if you have a GET request which has the form of a request=action parameter, then your server-side script must process this request by using its HTTP parameter handling (in PHP, you can either use $_GET or $_REQUEST).

Personally speaking, I prefer to use $_REQUEST because it doesn't matter if the request is GET or POST. Most PHP frameworks, like Zend, have specific classes to handle Ajax requests, so it's better to stick to those frameworks if you want to spare some time instead of worrying about the underlying implementation of a MVC pattern. Anyway, Stoyan's article is really useful, especially if you want to buy some little Ajax application.

jQuery: form submission with Ajax

One of the most confusing parts of jQuery's study is actually the submission of a form through Ajax. More specifically, developers sometimes don't understand the difference existing between return false and preventDefault(). Both of these approaches can be used to prevent a form from executing its default action, that is, making a browser open the resource specified in the action attribute.

There's a fundamental difference between these two methods: return false entirely disables the submission of a form, whereas preventDefault() only prevents a browser from fetching the resource specified in the action attribute. If you use the first method, then you will be able to submit the form only once, because any further action will be disabled. Imagine what would happen when you have to validate a form through Ajax: if there are some user errors, then a user will correct all the fields containing errors but in some cases he won't be able to submit the form again, because the submission has actually been disabled.

Instead, if you use preventDefault(), only the default action of the form will be disabled, but not its submission. So here's the correct approach:

$('#testForm').submit(function(e) {
      // retrieve form data

            // use Ajax

Google stopped indexing Blogspot

It seems that Google has apparently a problem with indexing new posts on Blogspot since October 19, 2010. This issue has been reported on Google's and Blogger's forums where, very kindly, Google's developers answered to tell that yes, there is a problem and yes, the problem has been reported to the technical staff. So we bloggers are all waiting. However, this problem seems to be more widespread than it could seem. In fact, many other blogs have been affected in the last few hours, not just those on Blogspot. I'll tell you more when I get more information about it.

In defense of browser implementors

After several years of web development, plus two years of C++ programming, I have to confess that I do not understand why web developers sometimes blame browser implementors. In many web tutorials is repeated the expression "it's not rocket science" to denote something that's easy to understand and use effectively. Well, implementing a web browser is something very similar to rocket science, in the sense that we're talking about extreme complexity here, not some fancy effects that you can achieve with some jQuery's plugin.

We're talking about thousands and thousands lines of code, broken down in several components and subcomponents, something that, if downloaded, occupies hundreds megabytes of disk space. We're talking about the inner interaction of components with each other, something that from a simple URL resolution and DNS querying leads to a complete page layout. We're talking about network interfaces, memory management, OS interfaces, interface design, web standards implementation (from parsing to rendering), user interface, widgets, extensions and so on.

What's more, how these web developers who criticize implementors would implement web standards themselves? It's easy to write float: left but it's incredibly harder to make it properly work on a web page. It's easy to use jQuery on our documents, but let's stop just a second and think about how much efforts are required to make $('#test + #foo') select its target element. Now they may say: "Well, this is not our job.". Sure, but why don't you try to help instead of complaining? Why don't you create some useful test case for filing a bug? Why don't you try to analyze a broken web site and report it? Never complain: cooperate.

This is probably the strongest post I've ever written on this blog but I do believe that cooperation is the only way to get the results we all want: better browsers, better sites.

jQuery: CSS properties used in animations

Most web developers think that jQuery animations work only thanks to the animate() method. Although this is true to some extent, it's worth saying that jQuery animations couldn't take place without the fundamental aid of CSS properties. CSS properties, in fact, help jQuery to animate HTML elements in several different ways. For example, width and height are useful when creating horizontal and vertical sliding effects, respectively. Example:

$('#test').animate({width: '0px'}, 'slow');
$('#test').animate({height: '0px'}, 'slow');

In the above code, the width and height of a given element have been reduced to 0. This is exactly the same visual effect of the slideUp() and slideDown() methods. The effect mentioned earlier is progressive, in the sense that the animate() method progressively subtracts pixels from the overall width or height of an element until it reaches 0, and then stops.

Other useful CSS properties are those related to floating, overflow and positioning. The float property often works together with overflow, especially when you have to create an horizontal slider. First, you specify on the parent element a width that equals only the width of the first child in a series. Then, with the overflow property, you actually hide the other child elements that will be later revealed by a subsequent jQuery action.

Also positioning properties are important. For example, to create the effect of an horizontal movement, you can declare position: relative on the target element and then, using the animate() method, change its horizontal offset by using either the left or right property. Of course you can add even more effects by using other CSS properties as well.

jQuery animations and Internet Explorer bugs

I had to create a smooth slide effect on two boxes using jQuery and its animate() method. The basic HTML structure is as follows:

<div id="container">

    <div id="box-a"></div>
    <div id="box-b"></div>


And here are the attached styles:

#container {
 width: 300px;
 height: 200px;
 background: #ccc;
 position: relative;
 top: 12px;
 overflow: hidden;

#box-a {
 width: 300px;
 height: 200px;
 float: left;
 position: relative;
 background: orange;

#box-b {
 width: 0px;
 height: 200px;
 float: left;
 position: relative;
 background: gray;

Also the related jQuery code is pretty straightforward:

$(document).ready(function() {

    $('#run').click(function() {
        $('#box-a').animate({position: 'absolute', left: '0px', width: '0px'}, 'fast'); // IE8- can't handle position: absolute here
        $('#box-b').animate({width: '300px'}, 'fast');
 return false;


To create our sliding effect we first reduce the width of the first box to 0 and then we set the width of the second box to a given length. Notice that the first box has been absolutely positioned. That's the tricky part for Internet Explorer 8 and lower: it can't handle the vertical offset of the first box and return a JavaScript error (error code 0). Simply remove the declaration position: absolute and you get the desired result even on IE. You can see a live test here.

jQuery: custom filter selectors

jQuery's custom filter selectors usually take the form of :selector. This kind of selectors can either be used alone or attached to a given element. With the aid of the $.expr[':'] pattern we can actually create our custom filter selectors. For example:

$.expr[':'].floats = function(element) {
  return $(element).css('float') !== 'none';

The above code selects only those elements whose CSS float property is set on a value different from none (that is, the elements are floated). Usage:

var $floats = $('div:floats');
var $notFloats = $('div').not(':floats');

As you can see, our newly created custom filter selector behaves exactly as a normal jQuery's filter selector. For more advanced tests and example, visit http://jquery.malsup.com/expr/.

jQuery: the addClass() and removeClass() methods

As their name says, the jQuery's addClass() and removeClass() methods simply add and remove classes on a given element, respectively. However, they differ greatly in how they work. In fact, the addClass() method makes use of the className property and some regular expressions to attach one or more classes to an element. Example:

$('#test').addClass('foo'); // adds the class 'foo'
$('#bar').addClass('foo bar'); // adds the classes 'foo' and 'bar'

You can attach multiple classes to an element by simply providing a space-separated list of valid class names. But the real interesting thing happens when you remove a class through the removeClass() method. Example:

 $('#test').removeClass('foo'); // removes the class 'foo'
$('#bar').removeClass('foo bar'); // removes the classes 'foo' and 'bar'

To remove classes, jQuery doesn't use the core DOM method removeAttribute() because of the backward compatibility with Internet Explorer 6. Instead, it uses regular expressions to replace the value of the class attribute with an empty string. If you take a look at the class attribute after using this method, you will see something like this:

<div id="test" class=""></div>
<div id="bar" class=""></div>

As you can see, the class attribute is still present in the DOM, but it has no impact on page layout because its value is empty.

HTML5: case-sensitivity and the DOM

We read from the DOM Level 2 HTML specifications:

1.3. XHTML and the HTML DOM

The DOM HTML Level 1 API were originally intended to be used only for HTML 4.01 documents. The APIs were defined well before XHTML 1.0 became a specification, or before it was worked on by the HTML Working Group. From the DOM point of view, The biggest difference between HTML 4.01 (and earlier) and XHTML 1.0 is that XHTML is case sensitive, whereas HTML 4.01 is case insensitive. The HTML case insensitivity is also reflected in the DOM HTML API. For instance, element and attribute names are exposed as all uppercase (for consistency) when used on an HTML document, regardless of the character case used in the markup. Since XHTML is based on XML, in XHTML everything is case sensitive, and element and attribute names must be lowercase in the markup. Developers need to take two things into account when writing code that works on both HTML and XHTML documents. When comparing element or attribute names to strings, the string compare needs to be case insensitive, or the element or attribute name needs to be converted into lowercase before comparing against a lowercase string. Second, when calling methods that are case insensitive when used on a HTML document (such as getElementsByTagName() and namedItem()), the string that is passed in should be lowercase.

Note: The interfaces provided in this document are only for HTML 4.01 and XHTML 1.0 documents and are not guaranteed to work with any future version of XHTML.

So I've created a simple test to check what is the actual behavior of web browsers when dealing with HTML5 that, as you know, is case-insensitive. The markup is pretty simple:


And here is the basic DOM test:

window.onload = function() {

   var p = document.getElementsByTagName('p')[0].firstChild.nodeValue;
   var div = document.getElementsByTagName('div')[0].firstChild.nodeValue;

   alert('Lowercase p is: ' + p);
   alert('Uppercase div is: ' + div);


As you can see, I've specified a reference to the div element using a lowercase notation, though the element itself is actually in uppercase letters. All browsers, except Firefox 3.6, execute correctly the above code. Firefox 3.6 simply returns null. So the question is: what will be the default behavior of Internet Explorer 9 for such cases? Time will tell.

Reading books on web development

Reading books on web development is not a required feature for a good developer but it can actually improve our knowledge of how web standards work. I've read more than 50 books on web development so far, including publications on CSS, DOM, JavaScript, XML, XSLT, SVG, jQuery, Prototype, plus many books on PHP, Python, C++, information architecture, usability, browser development and accessibility.

What have I learned? Very much, indeed. The fact is that these books are carefully written, extensively tested and proved to be actually valid in most scenarios. Although people tend to consider paper books as obsolete, I think that it's still quite relaxing lying in the bed before falling asleep with a good book to read. By doing so, you can dramatically increase your level of technical background with a minimum effort.

Generally speaking, these books are written in a very simple language, full of examples (not to mention the downloadable code that comes together with each publication) and with a step-by-step approach. It's also worth mentioning the fact that authors are always great developers (Eric Meyer, John Resig, Nicholas Zakas, just to mention few) with a strong technical background and a vast working experience.

So here's a little piece of advice: read! There's nothing to lose and everything to learn.

JavaScript: object cloning and the Factory pattern

The Factory pattern is used in traditional OOP languages to get an instance of the current object or class. A rough implementation in JavaScript would be the following:

function A() {

    this.foo = 'Foo';
    this.getInstance = function() {
        return new A();


The getInstance() method now returns an instance of its class. Just to reinvent the wheel, we can make some further tests to check whether we can use the returned class instance to perform object cloning:

var myA = new A();
var B = myA.getInstance();

B.prototype = A.prototype;
B.prototype.test = 'Test';

alert(B.foo); // alerts 'Foo'
alert(B.test); // alerts 'Test';
alert(A.test); // alerts 'undefined';

Associating the prototype property of the second class with a single instance of the main class results in a rough cloning of the aforementioned class. The B class correctly inherits from the A class, but the A class has not been touched. In fact, trying to access the test property we get undefined. As I said earlier, this was just a test and the result is pretty trivial.

CSS: negative text indent

The text-indent property can be actually used to create a nice effect of hanging text, that is, a line of text that protrudes out of its main container. Suppose, for example, that we have some level-2 headings. We can use negative text indentation this way:

h2 {

    font-size: 1.6em;
    text-transform: uppercase;
    margin-bottom: 0;
    color: #444;
    letter-spacing: 0.1em;
    text-indent: -1em;


Bear in mind that the text-indent property works only on the very first line of a block level element. However, this solution doesn't work properly in Internet Explorer 6, because this browser will crop the protruding text. A quick-and-dirty solution for IE6 consists in acertain amount of left padding added to the main container in order to compensate the opposite action of the negative indentation. Unfortunately, in most cases the desired effect will be lost on this browser. You can see the final result of the above code below.

CSS files maintenance

Maintaining CSS files is sometimes a tedious and difficult task, especially when you didn't take care of the inner organization of your style sheets. There are a few tips and gotchas for doing this that I'd like to summarize below.

Use comment blocks

Comment blocks use CSS comments to break down a style sheet in several different parts. Generally speaking, these parts are grouped together by their internal function within a CSS file. For example, CSS classes go in a distinct group, general HTML element in another one and so on. Here's an example:

/* @group HTML elements */


/* @end */

/* @group CSS classes */


/* @end */

As you can see, each group is marked up by a starting at-tag (@group), followed by a short description and then closed by another at-tag (@end). These tags serve as internal flags for a quick text search in your CSS editor.

Do not use @import

Imported style sheets have two major disadvantages:

  1. they're difficult to manage from the point of view of cascade and specificity
  2. they slow down your site performance by forcing browsers to perform multiple GET requests at once.

Use metadata

It's always useful to put some metadata information at the very beginning of your CSS files, especially when you're working in a development team where other developers may have to use your style sheets. A good example of such metadata are the initial comments put by every Wordpress theme inside the main CSS file.

Explain hacks

If you're going to use CSS hacks, just write down a brief explanation on the line (or lines) where you use such hacks. This is always a good coding practice, because when you look through your CSS after a while, you need to understand clearly what you wrote before. This is particularly useful when you're dealing with large CSS files.

PHP: encoding of a CSV file for Excel

I'm working on a MySQL database where all tables are encoded in UTF-8. One of the most required tasks on this database is creating downloadable CSV files to be read on Microsoft Excel. Creating a CSV file from a database is almost trivial, thanks to the PHP's fputcsv() function that parse an array and returns a formatted CSV line. The actual problem here is the target encoding, that is, the character set that MS Excel is able to handle.

First surprise: Excel is not able to handle properly UTF-8 characters if you don't change some of its default import settings. Of course we can't ask our clients to change their program settings when they download something from our website. Fortunately, there's a trick: Excel's default encoding is Windows-1252, so we have only to convert our UTF-8 characters to Windows-1252.

Since we're dealing with an array of values, we create a function that will be passed to array_walk() so that each value will be properly converted:

function excelEncode(&$value, $key)
  $value = iconv('UTF-8', 'Windows-1252', $value);


array_walk($excel_values, 'excelEncode');

By using the iconv() function we make sure that every single array value is properly encoded in a format that Excel can handle by default. Is there a less verbose way? Yes: just use the proper charset string on your header() function when you output a CSV file. This is the most quick and easy solution.

XML: avoiding namespace collision

XML namespaces were originally designed to avoid confusion between elements sharing the same characteristics. However, namespace should be created very carefully in order to avoid any possible collision. The first thing you need to bear in mind is that namespaces must have an higher degree of specificity than generic or public namespaces. For example, this is a perfectly valid XML namespace:

<document xmlns="http://www.site.com/ns/document" />

The problem with this namespace, however, is that is too generic, thus allowing for a possible collision. Instead, you should always choose a more specific namespace, for example by using the name of your website or web application, like so:

<document xmlns="http://onwebdev.blogspot.com/ns/elements/document" />

It's still true that other persons can actually use your namespaces on their websites, but it's also true that using a major level of specificity adds more semantics to your namespaces and, consequently, makes the risk of namespace collision less likely. Bear in mind that the purpose of namespaces is not trying to have absolutely unique IDs, but avoiding confusion between resources that may feature similar characteristics.

Accessibility support to HTML5

Today Roberto Castaldo posted a message on the Webaccessibile Italian mailing list sharing his translation of an invaluable resource of Steven Faulkner about HTML5 and accessibility.

More precisely, Steven's site contains a comparative table that shows the current accessibility support to HTML5 elements in the most used web browsers. If you take a look at the table, you will probably notice that almost all HTML5 elements listed there are not supported by browsers from an accessibility point of view. Although these elements are actually implemented, there are no additional accessibility features attached to them. For example, the video and audio elements lack of support to certain keyboard shortcuts in all browsers.

If we want to learn a lesson from this, we should stick to traditional HTML 4 and XHTML elements as long as browsers extend their support to the accessibility features required to make HTML5 elements fully accessible even to assistive technologies. Bear in mind, however, that HTML 4 elements are perfectly valid HTML5 elements, so there are no problems with this approach.

CSS: differences between descendant and child selectors

I noticed that many developers who start coding in CSS sometimes get confused by descendant and child selectors. In a nutshell: descendant selectors select an element that is contained within another element, disregarding its position in the DOM tree. On the contrary, child selectors select an element only when it's the direct child of its parent. For example, given the following structure:




You can use descendant selectors this way:

div em  {
  background: yellow;

Notice that in this case the matching occurs without taking into account the order of the DOM tree. Instead, if you use child selectors, you have to write this:

p > em {
  background: yellow;

That's because the em element is the direct child of the p element. In this case the inner order of the DOM tree is relevant.

Complete email validation

Email validation is one of the most common tasks required when building up a website. The problem with this task is that the overwhelming majority of websites don't use a complete email validation but only a partial one. To be complete, email validation must:

  1. check whether the email format provided by the user fulfills the formal requirements contained in the specifications (RFC 2822)
  2. check whether the email address actually exists and it's active.

The first point requires the use of string manipulation and analysis. Either you choose to use string methods or regular expressions, you must stick to the format specified in the RFC 2822. I've seen in many books and many tutorials regular expressions that were incomplete and didn't conform to the specifications. The only exception is contained in the manual PHP Cookbook, where email validation is treated in full, mainly from the point of view of the requirements of the RFC 2822. Of course, the same rules apply to client-side validation.

Finally, validation would be incomplete if we weren't sure that a given email address exists and it's alive. This particular subtask can only be performed by a server-side language. There are many functions and methods available in several server-side languages that allows you to do this. This kind of verification should be always performed after the first format check, not before.

Using JSON as a blog RSS feed

JSON is gaining its momentum. Many websites have started using this format as their default format of choice for data exchange. One of the main reasons behind this choice is that JSON is a simple and lightweight format. RSS, on the other hand, is basically XML, implying that this format is more suitable when you have to deal with complex data structures, since XML is particularly useful for adding semantics to describe data (think about RDF, for example).

An RSS feed, in its basic structure, is actually simpler than most developers think. For example, take a look at the following excerpt taken from a sample RSS feed:

<?xml version="1.0"?>
<rss version="2.0">
      <title>Liftoff News</title>
      <description>Liftoff to Space Exploration.</description>
      <pubDate>Tue, 10 Jun 2003 04:00:00 GMT</pubDate>
      <lastBuildDate>Tue, 10 Jun 2003 09:41:01 GMT</lastBuildDate>
      <generator>Weblog Editor 2.0</generator>
         <title>Star City</title>
         <description>How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia's <a href="http://howe.iki.rssi.ru/GCTC/gctc_e.htm">Star City</a>.</description>
         <pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate>
      <!--more item elements here-->

As you can see, this is not a too complex structure. Using JSON, you can rewrite the above feed like so:

{"rss": {

    "channel": {
        "title": "Liftoff News",
        "link": "http://liftoff.msfc.nasa.gov/",
        "description": "Liftoff to Space Exploration",
        "language": "en-us",
        "pubdate": "Tue, 10 Jun 2003 04:00:00 GMT",
        "lastbuilddate": "Tue, 10 Jun 2003 09:41:01 GMT",
        "docs": "http://blogs.law.harvard.edu/tech/rss",
        "generator": "Weblog Editor 2.0",
        "managingEditor": "editor@example.com",
        "webmaster": "webmaster@example.com",
        "item": [
             "title": "Star City",
             "link": "http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp",
             "description": "...",
             "pubdate": "Tue, 03 Jun 2003 09:39:21 GMT",
             "guid": "http://liftoff.msfc.nasa.gov/2003/06/03.html#item573"
            // more items here


This is only a showcase to demonstrate that some peculiarities of the JSON format are really interesting from a development point of view. Most of all, a JSON feed is noticeably faster to parse than a normal XML/RSS feed and requires less resources. Further, all server-side languages include some methods or functions to encode and decode JSON data. Finally, it's worth to be mentioned that now the vast majority of web browsers are able to parse JSON natively.

CSS: writing efficient user style sheets

One of the most neglected and underused features of CSS are user style sheets. This feature allows our visitors to customize the rendering of our documents without worrying too much about the styles already specified by an author. Here are some peculiarities of user style sheets.

  1. Cascade

    CSS styles provided in a user style sheets always win when there are conflicting rules. In other words, when an author specifies a CSS rule and a user tries to override it, then the user will win. I recommend you to always use the !important declaration to make sure that your styles will have the highest priority.

  2. Semantics

    User style sheets work at their best when their target pages are structured properly. For example, to help users with customizing our pages, we can provide different IDs on the various body elements of different pages. This helps a lot, for example by writing a rule like this:

    body#home {
      background: #fff !important;
      color: #000 !important;

    However, the overwhelming majority of web documents are basically tag soup, because they're full of markup errors, deprecated HTML elements and nested tables. But user style sheets can actually deal with this worst-case scenario, like so:

    font {
        color: #000 !important;
        font-size: 1em !important;
        font-family: sans-serif !important;

    Another typical case is when a document contains non-standard elements, like marquee or blink:

    marquee {
        -moz-binding: none !important;
        overflow: hidden !important;
        display: inline !important;
    blink {text-decoration: none !important;}

    Anyway, not all of these elements can be actually prevented from showing their default behavior. This is particularly true in Internet Explorer.

Almost all browsers allow for the use of user style sheets. I think that the later adoption of this kind of feature is mainly due to the fact that most users don't have a basic knowledge of CSS required for this task.

CSS: multiple classes

CSS classes can actually be combined together on the same element to get interesting results due to the cascade. As I said in an earlier post, CSS classes can be used to create cumulative styles, thus resulting in a more flexible and reusable code.

For example, suppose that you have some floated images. You want that some of these images show a doubled border and in this case there are two classes that can be joined together:

.alignleft {
  float: left;
  margin-right: 5px;

.picture {
    padding: 5px;
    border: 5px double #aaa;

Then you add the above classes on an img element, like so:

<img src="pic.gif" alt="Picture" class="alignleft picture" />

However, there are a few things to keep in mind when using a solution like this. First, you should always specify style rules that don't conflict with each other. If you don't do so, then the cascading rules will decide what rule is the winner (e.g. when a class comes first or later in the source or when a rule is followed by an !important statement). Second, Internet Explorer 6 has a really poor support to multiple classes, so it's sometimes very difficult to select an element with two or more classes applied to it.

Anyway, if you aren't really worried about these issues, then multiple classes can actually be a useful way to apply styles in an elegant, reusable and semantic way.

HTML5 is not ready

There's been a lot of talking about the recent announcement of the W3C about the early adoption of HTML5. Though the advice of not sticking too early to HTML5 seems absolutely reasonable, there are some things that need to be cleared. First, W3C's announcement is mainly related to the fact that HTML5 is still a draft. This means that in a not too remote future some changes might be added to the specifications, thus resulting in invalid pages.

Second, HTML5 has been designed to be fully backward-compatible. Although most of HTML5 elements are actually valid HTML 4 elements, there are some brand new elements (and attributes) that browsers are not able to recognize. When a browser encounters an unknown HTML element, it simply treats it as an anonymous element with no default styles and no predefined actions. This is the case, for example, of the abbr element in Internet Explorer 6. Some developers think that the presence of unknown elements makes a browser switch to quirks mode. This is only a rumour.

The real problem, instead, actually involves assistive technologies that parse and render an HTML5 document. For example, a screen reader that stumbles on an article element doesn't know in advance how to handle it. As a result, it's very likely that a screen reader will ignore completely such an element together with all of its contents.

Instead, DOM scripting should work fine, because unknown elements can actually be treated as a subset of the generic HTMLElement interface, though some non-standard features (such as the innerHTML property) should be carefully tested.

To summarize: W3C's experts didn't say "do not use HTML5" but "use it carefully". For example, you should use common HTML 4 elements to make sure that your documents are still backward-compatible. Instead, using an HTML5 DOCTYPE is safe, because not-supporting browsers do not switch to quirks mode when they encounter it. I think we should wait until we can use HTML5 in a more complete way.

jQuery and JavaScript inheritance

A couple of months ago I found this interesting post on JavaScript inheritance which shows an alternate way to get the same results achieved through the methods proposed by Douglas Crockford and Kevin Lindsey. This solution is based on the work of Troels Knak-Nielsen and is as follows:

function copyPrototype(descendant, parent) {
    var sConstructor = parent.toString();
    var aMatch = sConstructor.match( /\s*function (.*)\(/ );
    if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; }
    for (var m in parent.prototype) {
        descendant.prototype[m] = parent.prototype[m];

The author of the post then quotes Troels who says:

First off – I fully understand and agree to the point of not extending language functionality. That said I think the point in relation to javascript and inheritance is often misunderstood. It is central to javascript that it is a "typeless object-oriented language". This goes for ECMAscript3.0 all the same. Where people most often get it wrong is when they mistake prototypes for classes – they are not.

In a typed OO-language the objects code lies with the class – objects are just instances. In js, the code lies in the object. Therefore, the object is not tied to the prototype. It is ok in js to manipulate the prototype runtime, even after objects has been instantiated. Consider doing that with a typed language.

Anyway. I have been working a lot with js recently, and found that one-level inheritance is simple enough using prototypes, but further inheritance cause trouble. I guess you came to the same conclusion with JPSpan. My first googling on the subject turned up a lot of wierd hacks, that I don’t appreciate. I eventually invented a solution witch I use, and witch I’m very happy with. It may look as a hack, but it works so well, that I kind of forgive it for that.

To defend myself further I’ll point out that it’s not a language extension, if you just understand what it does. It’s merely a utility that extends a prototype – Which should not be confused with class inheritance (though the result is the same).

Apparently jQuery comes up with a somewhat similar solution for handling inheritance in JavaScript: the $.extend() method. The inner structure of this method is the following:

jQuery.extend = jQuery.fn.extend = function() {
 // copy reference to target object
 var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;

 // Handle a deep copy situation
 if ( typeof target === "boolean" ) {
  deep = target;
  target = arguments[1] || {};
  // skip the boolean and the target
  i = 2;

 // Handle case when target is a string or something (possible in deep copy)
 if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
  target = {};

 // extend jQuery itself if only one argument is passed
 if ( length === i ) {
  target = this;

 for ( ; i < length; i++ ) {
  // Only deal with non-null/undefined values
  if ( (options = arguments[ i ]) != null ) {
   // Extend the base object
   for ( name in options ) {
    src = target[ name ];
    copy = options[ name ];

    // Prevent never-ending loop
    if ( target === copy ) {

    // Recurse if we're merging object literal values or arrays
    if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) {
     var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src
      : jQuery.isArray(copy) ? [] : {};

     // Never move original objects, clone them
     target[ name ] = jQuery.extend( deep, clone, copy );

    // Don't bring in undefined values
    } else if ( copy !== undefined ) {
     target[ name ] = copy;

 // Return the modified object
 return target;

As you can see, the jQuery's approach varies significantly in many aspects, since this method is able to recognize the type of the values passed in and react accordingly. The final result is always an object whose properties and methods are actually the sum of the objects passed to the method. For example, if we have two objects like these:

var A = {
    foo: 'Foo',
    bar: function() {

function B() {
    this.loc = location.href;

We can create an object named C with a single statement:

var C = $.extend(A, B);
C.bar(); // alerts 'Foo'
alert(C.loc); // alerts the current page location

This method is actually much simpler in its practical use than the previous one, mostly because it allows us to get more control over what happens behind the scenes of JavaScript inheritance. Further, it prevents beginners from getting confused by the impressive amount of technical details which come along with JavaScript inheritance.

jQuery: checking whether elements exist

Checking whether elements exist on a given document is a common feature requested by many developers. In fact, some jQuery and JavaScript actions often can actually take place only when a given element (or a set of elements) is present on a given page. Unfortunately, there are some problems with some DOM Core methods.

For example, getElementById() returns null when an element is not present, whereas getElementsByTagName() returns nothing in that case. So the following code works as expected:

var elem = document.getElementById('test');
if(elem !== null) {
    // do something

but this one returns nothing:

var elems = document.getElementsByTagName('div');
if(elems) {
  // do something

With jQuery, we can easily overcome this problem by using the size() method of the wrapped set, like so:

if($('div').size()) {
  // do something

This method returns the number of elements ( a DOM NodeList) contained in the specified jQuery context. For a better performance, you can also use the length property. Note, however, that this property is also available for common DOM NodeLists, so that our previous example can actually be rewritten as:

var elems = document.getElementsByTagName('div');
if(elems.length > 0) {
  // do something

Styling blog dates with CSS

Dates are an often neglected part of a blog layout. If styled properly, they can actually enhance the visual appeal of our layouts. CSS offers a great control over page elements especially when dealing with blocks containing short text. In our example, we'll examine the case of a date containing the string "October 8, 2010". As you can see, we have a month, a day and a year. To start with, here's how our markup should look like:

<div class="post">
    <span class="blog-date">October 8, 2010</span>
    <h2>Post title</h2>

In this case, the blog date comes before the post title and is a simple span element with a class called .blog-date. We want to add a background image to our date just for creating the visual effect of a calendar date. Our CSS styles are as follows:

body {
  margin: 0 auto;
  padding: 2em 0;
  background: #fff;
  color: #333;
  font: 76%/1 Arial, sans-serif;
  width: 40%;

div.post {
  height: 100%;
  padding-bottom: 0.3em;
  border-bottom: 1px dashed #555;
  font-size: 1.1em;

div.post h2 {
  float: left;
  margin: 0;
  font: normal 3em Georgia, serif;
  color: #666;
  padding-left: 5px;
  padding-top: 10px;
  text-transform: uppercase;
  letter-spacing: 0.1em;

div.post span.blog-date {
  float: left;
  display: block;
  width: 79px;
  height: 50px;
  padding-top: 30px;
  font-size: small;
  text-align: center;
  font-weight: bold;
  background: url(img/date.png) no-repeat 0 0;
  line-height: 1.3;

div.post p {
  clear: both;
  margin-top: 0;
  padding-top: 1em;
  line-height: 1.4;

Both post date and title have been left-floated. The post title doesn't actually need to have a stated width, so here browsers will apply the shrink-to-fit algorithm, thus assigning to the floated element only the space necessary to host its contents. Instead, our date needs to be dimensioned, since our background image is 79 x 80 pixels. Further, we want the date text appear horizontally and vertically centered inside the image, so we specify an height of 50 pixels and then we add 30 pixels of top padding so that the overall height of our block will be exactly 80 pixels.

But there's a catch: since our elements are floats and there's no container element for them, we need to clear all subsequent paragraphs. To avoid bugs in Internet Explorer 6 and 7 (especially those related to the correct calculations of collapsing margins on cleared elements), we've actually zeroed the top margin of paragraphs, using top padding with a similar value. You can see the final result below.

HTML5: use of aside and article

HTML5 comes with a couple of new elements that actually enhance our websites by allowing us to add more semantics to our page structures. Two interesting elements are aside and article. As their names say, these elements mark up the secondary and the primary content of a page, respectively.

In the old days of HTML and XHTML, we were used to write something like this:

<div id="contents">

    <div class="article"></div>
    <div class="article"></div>
    <div id="content-sub"></div>


In this case, we have two .article elements and a #content-sub element. Instead, with HTML5 we can write:

<div id="contents">



By doing so, we get rid of generic div elements and we actually add an extra layer of semantics to our documents.

CSS: styling emails

Almost a year ago I made some tests with CSS and emails for a personal project involving the creation of HTML templates to be used with email messages. Here are some of my remarks on this subject.

Don't use inline styles

Inline styles are redundant and led to a poor maintainability. You should always use external style sheets to accomplish this task. Just create a CSS file for your email templates and use it through the link element.

Test your layout dimensions

You should always make sure to test the dimensions given to your layout elements. As a rule of thumb, fixed-width layouts work always fine, although you can even use elastic and fluid layouts. The problem here is that the rendering engine of an email client sometimes differs greatly from a browser's rendering engine.

Be careful with font sizing

Generally most developers use fixed font sizing on emails. This is fine, but it poses some accessibility problems if the email client doesn't allow a user to resize fonts when their dimensions are expressed in pixel. I didn't test this extensively, so be careful.

Background images

Most email clients pose some limitations to the use of background images (and images in general). For example, I noticed that Thunderbird didn't show a background image set via CSS, while Outlook did. This is another feature that needs to be tested very carefully.

Positioning schemes

This is another thing that I didn't test extensively. Web developers generally tend to use tables in order to create a cross-device pagination for their emails. Theoretically speaking, it should be possible to use floats and positioning on emails, although these features should be carefully tested.

Who I really am

Basically, I'm a person whose childhood dream was doing a job where you can help other people. On August 12, 2006 I wrote down on a piece of paper the following quotation from Matthew 25, 35-41:

For I was an hungred, and ye gave me meat: I was thirsty, and ye gave me drink: I was a stranger, and ye took me in: Naked, and ye clothed me: I was sick, and ye visited me: I was in prison, and ye came unto me. Then shall the righteous answer him, saying, Lord, when saw we thee an hungred, and fed thee? or thirsty, and gave thee drink? When saw we thee a stranger, and took thee in? or naked, and clothed thee? Or when saw we thee sick, or in prison, and came unto thee? And the King shall answer and say unto them, Verily I say unto you, Inasmuch as ye have done it unto one of the least of these my brethren, ye have done it unto me.

I didn't found elsewhere a passage like this, clearly expressing my old childhood dream with words. I always bring that paper with me.

CAPTCHA images considered harmful

Just a couple of minutes ago I've updated my profile on Amazon by providing an alternate email address. The main problem encountered during this procedure was recognizing the correct character sequence in the CAPTCHA image. I had to try several times before typing the correct sequence. So my point is: if a sighted user has encountered so much problems with CAPTCHA images, what will happen to a visually impaired person who tries to fill in the form?

I'm not talking about blind users who can still get an alternate version of the CAPTCHA. I'm simply talking about persons who do not have a perfect sight. Honestly, I was frustrated by this. I kept typing my password, my new email and then.. nothing! Or, even worse, an error message claiming that the characters inserted weren't correct. Now you may ask if there's a feasible alternative to images. The answer is... yes! Simply put, use a textual alternative, for example by asking a simple question that only a human reader can understand (e.g. "What is the capital of the United States?").

What's more, you can actually get rid of a lot of server-side procedures used to creating, changing and inserting the CAPTCHA image. The only problem with this approach lies in the correct choice of some good questions. Anyway, surely we'll prevent our users from being frustrated when they try to decipher the CAPTCHA image and get some error.

An alert box with CSS

I've just finished to upload a series of old notes on CSS development which include a demo showing how to build an alert box with CSS. This demo makes use of CSS system colors to create a platform/OS-dependent layout for the alert box.

The main problem encountered here is that not all browsers support system colors properly (for example, it doesn't work in Chrome). Further, system colors have been deprecated in CSS3 so for future compatibility you should avoid this practice. Instead, you can use JavaScript platform detection to provide the proper layout to each OS (yes, the CSS way it's a lot neater, but still).

CSS3 transformations: rotate

One of the newly introduced features in CSS3 is the concept of trasformations which allows developers to apply the same rendering effects once available only in SVG to common HTML page elements. For example, if we want to apply a rotation to a simple box, now we can write the following:

#rotated {
    width: 200px;
    height: 150px;
    background: orange;
    margin: 2em auto;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    transform: rotate(-10deg);

And this is the result in all supporting browsers:

This feature is currently supported by the latest versions of Firefox, Chrome and Safari. Note, however, that I've specified the vendor-specific extensions first and then the standard property. By doing so, we make sure that a browser will use the standard property if it's supported.

Adding SVG to an XHTML document

In order to properly add SVG to an XHTML document there are some basic requirements that need to be satisfied. First of all, your host document (that is, the XHTML document that contains one or more SVG elements) must be served as application/xhtml+xml. Second, you must choose the proper DTD from this W3C page.

The second requirement is very important. In fact, if you don't choose the correct DTD, your document won't validate. Many web developers think that they can simply add a svg element to any XHTML document. This is not the case, because if you take a look at the aforementioned W3C document, you'll notice that only certain DTDs allow SVG to be used within their definitions. More precisely, you should use a DTD that combines together XHTML 1.1, MathML and SVG itself. Further, you should decide whether SVG is the host language or not. In any case, always remember to choose the more suitable DTD.

Hiding and showing panels with jQuery

I just finished this website (a professional portfolio) where I had to hide and show content panels in an alternate way. The main problem I've encountered is basically to determine whether a panel is visible or not, that is, if its current state has been yet modified by a jQuery action.

When a visitor clicks on a tab, the corresponding panel must be revealed. Of course when this action takes place, all other visible panels must be hidden (and so on). Here's how this is done:

this.hideShowPanels = function() {
        var ids = [];
       $('#navigation a').each(function() {
           var $a = $(this);
    var id = $a.attr('href');
    $a.click(function() {
        for(var i=0; i<ids.length; i++) {
           if(id !== ids[i]) {
        if($(ids[i]).is(':visible')) {
      return false;

First, I get the ID attribute of each panel by reading the value of the href attribute of each tab. Then I add this value to the ids array, which will be used later. When a user clicks on a tab, the corresponding hidden panel is showed thanks to the slideDown() method. In the meantime, I loop through the ids array and check whether there are other panels (not the current one) that are in a visible state. If so, I hide them through the slideUp() method. This action occurs on each tab, which has the form <a href="#panel"></a>.

CSS3 multiple background images

CSS3 supports the concept of multiple background images on page elements. Instead, CSS 2.1 allows only one background image to be applied on elements. For example, if you wish to have a tabbed menu with a rollover effect on :hover, in CSS 2.1 you should use a markup like this:

<div id="navigation">
<li><a href="#"><span>Home</span></a></li>
<li><a href="#"><span>Articles</span></a></li>

Then you have to apply two separate background images, one on the a element and the other on the span element. CSS3 circumvents this limit by allowing you to use multiple background images directly on links, thus avoiding the use of a non-semantical additional element:

#navigation a {
      background-image: url("img/tableft.gif"), url("img/tabright.gif");
      background-position: 0 0, 100% 0;
      background-repeat: no-repeat;
      padding: 5px 15px 4px 11px;
      font-weight: bold;
      display: block;
#navigation a:hover {
      background-position: 0% -42px, 100% -42px;
      color: #fff;

The newly supported features are simply to understand: instead of specifying only a single value for each property, now you can add up to four values, using commas as separators. Another example are boxes with rounded corners. In CSS 2.1 you have to use a markup like the following:

<div id="box">
   <div id="box-top-right">
         <div id="box-bottom-left">
  <div id="box-content">

Again, you have to apply a separate background image on each nested element, starting from the outermost one. With CSS3 you need only one element and one single CSS rule:

#box {
  width: 240px;
  background-color: #d16c00;
  background-image: url("img/topleft.gif"), url("img/topright.gif"), url("img/bottomleft.gif"), url("img/bottomright.gif");
  background-repeat: no-repeat;
  background-position: 0 0, 100% 0,  0 100%, 100% 100%;
  color: #fff;
  padding: 10px;

This feature is currently fully supported by Firefox, Safari, Opera and Chrome. Internet Explorer will support it with the new incoming release.

CSS: table-based layouts are not dead

I just finished to watch the following video from Google, where one of their experts clearly states that Google doesn't care if you use a standard compliant approach to your layouts or an old-fashioned tabular one.

So what's the point in this? Should we continue to follow a standard approach to web development or a relic of a dark age when any website showed a banner claiming that "this website works better on browser X"? I think that Google is actually following a backward-compatible approach to SEO and website indexing. But what about accessibility? And what about other users who surf the web with an alternate browser or device?

If we should draw a conclusion from this, we should probably admit that all the good things that have been said about CSS-based layouts (SEO friendly, better SEO optimization, better indexing, better ranking and so on) are all myths. It seems that Google doesn't care too much if you use CSS or tables, HTML 3.2 or HTML 5. However, this is not Google's fault, because the overwhelming majority of web documents are still written in an obsolete, non-standard way (not to say that most of them are basically tag soup).

So that's author's fault. I hope that new evangelizations will come in the next few years to amend this. In the meantime, the battle goes on.

XML and accessibility

A year ago I took a seminar in Milan where I spoke on the future possibilities of XML when applied to blogs (you can see the slides here). Many people got impressed when I showed them how to create a blog entirely written in XML, transformed with XSLT and displayed with CSS.

In the meantime, I had a nice conversation with Livio Mondini, who pointed out some interesting remarks on my conference. First of all, XML poses some accessibility problems when it comes to screen readers. In fact, since XML has no predefined DTD, screen readers don't know in advance how to handle XML elements. Simply put, a screen reader will ignore the element together with its content.

I didn't test extensively what happens when you transform an XML document with XSLT. This would be a useful test to do. Theoretically speaking, a screen reader should be able to recognize the transformed XML element but only when the target format is HTML (which, of course, has a predefined DTD). However, since screen readers read only what a browser reads (that is, the output provided by a web browser), what happens when a browser doesn't support XML and XSLT properly? That's another interesting question.

In other words, if the current browser is Internet Explorer 6, which by default doesn't read XML unless you activate the correct linking to the MSXML library, what a screen reader will read? I can't test it myself because I do not have a screen reader installed on my computer. I leave this test to you. If you find out something interesting, please let me know.

CSS: how the clear property works

The CSS clear property works on elements that come near or after a floated element. Since a floated element affects the computation of horizontal space of a web document, this property re-establishes the normal flow of a layout. In fact, when an element is floated, all elements near it surround that element by placing themselves to its right or left outer edge.

For example, if an element is left-floated, all subsequent elements will be shifted to its right edge, while if an element is right-floated, all subsequent elements will be pushed to its left edge. Using Firefox's terminology, this is called float damage and it occurs when the computation of space is rearranged due to float action.

Of course web developers wished to have more control over this behavior. For that reason, the clear property was introduced in CSS 2 (back in 1998). This property performs a simple task: it puts back in the normal flow an element that comes near or after a floated element. For example, if you have a left-floated image and a paragraph that contains it, to clear the next sibling paragraph you can write:

p:first-child + p {
  clear: left;

By doing so, the sibling paragraph stops surrounding the floated image and it's displayed just under the first one. Curiously, this property can also be applied to float themselves. In that case, if you have more than one float on a line, this declaration prevents other floats from being displayed near the first one.

However, this property can actually cause some problems when it comes to vertical margins. For example:

p:first-child + p {
  clear: left;
  margin: 0.5em 0;

Browsers like Firefox, Safari, Opera, Chrome and IE8+ correctly calculates the amount of vertical space for the cleared element, while IE7 (and lower) add some extra space. You should always be aware of this fact when dealing with clearing and vertical margins.