Web typography with CSS3

In this post I'm going to show you how to improve the overall visual effect of a sample h1 element by using some advanced CSS3 properties, namely border-radius, box-shadow, text-shadow and transform. The default appearence of such an element is shown below.

Now let's augment its styles:

h1 {
        
        font: normal 3.5em Impact, sans-serif;
        letter-spacing: 0.2em;
        color: #fff;
        text-transform: uppercase;
        -moz-transform: rotate(-5deg);
        -webkit-transform: rotate(-5deg);
        -o-transform: rotate(-5deg);
        text-shadow: 3px 3px 3px #999;
        -moz-box-shadow: 3px 3px 3px #999;
        -webkit-box-shadow: 3px 3px 3px #999;
        box-shadow: 3px 3px 3px #999;
        background: #990;
        -moz-border-radius: 6px;
        border-radius: 6px;
        padding: 8px;
}

And this is the result:

As you can see, the most impressive effect is the rotation performed on the block counterclockwise.

CSS: styling a Twitter widget

In my previous post I've outlined the inner HTML structure created by the Profile widget of Twitter. In this post I'm going to show you how to take advantage of this structure to stylize a Twitter widget with CSS. First, we need an HTML wrapper that will contain our widget. It is as follows:

<body>

<div id="tweets">

    <!-- JavaScript here -->

</div>

</body>

The default appearance of such widget is shown below.

Now it's time to apply styles. Remember that we're dealing with JavaScript styles, so we need to override them:

#tweets {

    width: 300px;
    margin: 0 auto;

}

#tweets .twtr-widget,
#tweets .twtr-doc {

    width: 100%;
    height: auto;


}


#tweets .twtr-hd {

    background: #d40;
    color: #fff;
    -moz-border-radius: 6px 6px 0 0;
    border-radius: 6px 6px 0 0;
    font-family: Georgia, serif;
    

}

#tweets .twtr-hd *,
#tweets .twtr-hd h4 a {

    background: #d40 !important;

}

#tweets .twtr-hd h3,
#tweets .twtr-hd h4 {

    font-weight: normal;
    text-align: center;

}

#tweets .twtr-hd h3 {

    background: #fff !important;
    color: #333 !important;
    font-size: 1.5em !important;
    padding: 0.2em !important;
    -moz-border-radius: 3px;
    border-radius: 3px;

}

#tweets .twtr-tweet {

    background: #fff;

}

#tweets .twtr-tweet a:link,
#tweets .twtr-tweet a:visited,
#tweets .twtr-tweet a:hover {

    color: #c40 !important;

}

#tweets .twtr-tweet .twtr-tweet-text {

    border-bottom: 2px dashed #666 !important;
    padding-bottom: 4px !important;

}


#tweets .twtr-tweet .twtr-tweet-text p {

    color: #333 !important;

}

And this is the result:

As you can see, we made an abundant use of the !important statement to make sure that our styles will override the default ones.

How browsers support JavaScript frameworks

The most important thing you need to know about this topic could seem quite shocking: browsers are not supposed to support JavaScript frameworks. Basically, a browser must support only the ECMAScript standard (for its JavaScript engine) and the DOM specifications (for its DOM engine). Everything else is a plus. In other words, a JavaScript framework works because of the efforts of its developers for making it compatible with the greatest variety of browsers, not because browser implementors have tested this framework.

It's practically impossible for browser implementors to test extensively all the existing JavaScript frameworks. Even with a new browser release, this kind of tests (or regression tests) never take place. It's up to JavaScript coders to test their frameworks with the new browser release and fix bugs whenever they occur. So if your favorite framework shows some obtuse bugs in a newer browser release, you'll basically need to wait until these bugs will be fixed by the team that actually develops that framework. I know this it's hard to accept, but this is how things work with browsers.

JavaScript: structure of a Twitter widget

In this post I'm going to outline the inner structure of a Twitter widget from the point of view of the DOM structure created by the JavaScript code. We're going to use the Profile widget, whose embedded code is shown below:

<script src="http://widgets.twimg.com/j/2/widget.js"></script>
<script>
new TWTR.Widget({
  version: 2,
  type: 'profile',
  rpp: 4,
  interval: 6000,
  width: 'auto',
  height: 300,
  theme: {
    shell: {
      background: '#333333',
      color: '#ffffff'
    },
    tweets: {
      background: '#000000',
      color: '#ffffff',
      links: '#4aed05'
    }
  },
  features: {
    scrollbar: false,
    loop: false,
    live: false,
    hashtags: true,
    timestamp: true,
    avatars: false,
    behavior: 'all'
  }
}).render().setUser('yourusername').start();

This code generates a large amount of HTML elements. Most of them are presentational elements used to make the widget fit the page. They're as follows:


<div class="twtr-widget twtr-widget-profile" id="twtr-widget-1">

    <div class="twtr-doc">
    
        <div class="twtr-hd">
        
            <a class="twtr-profile-img-anchor" href="yoururl">
            
               <img class="twtr-profile-img" src="yourprofileimagepath">
            
            </a>
            
            <h3>Your Full Name</h3>
            
            <h4><a href="yourhomepath">your Twitter username</a></h4>
        
        </div>
        
        <div class="twtr-bd">
        
            <div class="twtr-timeline">
            
                <div class="twtr-tweets">
                
                
                    <div class="twtr-tweet">
                    
                        <div class="twtr-tweet-wrap">
                        
                        
                           <div class="twtr-tweet-text">
                           
                           
                               <p><a href="yourhomepath">your username</a> your tweet.</p>
                           
                           
                           </div>
                        
                        
                        </div>
                    
                    
                    </div>
                    
                    <!-- more tweets -->
                
                </div>
            
            
            <div class="twtr-ft">
            
            
                <div>
                
                    <a href="http://www.twitter.com/">
                    
                        <img src="widget logo path">
                    
                    </a>
                    
                    
                    <span>
                    
                        <a href="your home path">Join the conversation</a>
                    
                    </span>
                
                
                </div>
            
            
            </div>
            
            </div>
        
        </div>
    
    
    </div>


</div>

As you can see, we have a lot of CSS classes with the prefix twtr, so it won't be difficult to change the default layout of your widget by using CSS, provided that you respect cascade and specificity order.

jQuery: precedence of the load() and ready() events

At first glance the precedence of the load() and ready() events in jQuery should be really easy to understand. Many developers think that first comes the loading of the page and then the completion of the DOM. This is not the case. In fact, if you try something like this:

$(window).load(function() {

    alert('Load');

});

$(document).ready(function() {

    alert('Ready');

});

This will alert first "Ready" and then "Load", because DOM's completion comes first. If you want to preserve the correct order of both events, you should rewrite the above code as follows:

$(window).load(function() {

    alert('Load');
    
    $(document).ready(function() {

        alert('Ready');

    });

});

This turns out to be very handy when you have to perform some pre-caching and pre-loading of your own jQuery application.

jQuery: dynamic CSS floats

In this post I'm going to show you how to implement a set of basic animations using CSS floats and the animate() method of the jQuery library. Let's say that we have a series a boxes inside a container. The normal flow of the documents lay them out as normal blocks, one on the top of the other.

The secret here is not using the float property directly inside the animate() object, but rather in the callback function attached to it, like so:

$(document).ready(function() {
    
   $('#animate').click(function(e) {
    
        
        $('#container div').each(function() {
            
           $(this).animate({
            
               width: '100px',
               height: '100px',
               lineHeight: '100px',
               margin: '0 1em 0 0'
            
           }, 'slow', function() {$(this).css('float', 'left');});
            
        });
        
        e.preventDefault();
    
    
   });
});

If you use floating inside the style properties of the animate() method, you will get unexpected result. You can see this demo here.

HTML5: the script element

In HTML5, the script element no longer needs the type attribute. This attribute is actually useless, because a browser already knows how to handle the content of such element. So you can write something like this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>

alert('foo'); 

</script>

As you can see, there's no need of this kind of attribute anymore.

CSS: use of the @namespace rule

An interesting feature of CSS3 namespace selectors that came up during some of my random tests concerns the use of the @namespace rule. This rule looks like any other at-rule, except that it accepts two parameters instead of one. The first parameter is important, because it tells the browser from which element it must start to select elements through CSS selectors. The second parameter, instead, is simply the namespace URI you're going to use. In its pure form it looks as follows:

@namespace element 'URI';

Let's look at what happens with a sample XHTML document that contains only a single paragraph. In our first attempt, we'll try this:

@namespace html 'http://www.w3.org/1999/xhtml';
    
html|p {color: green}
body|p {color: red}
   

The text's color will be green because our namespace rule tells the browser to use the html element. Now let's try a different approach:

@namespace body 'http://www.w3.org/1999/xhtml';

html|p {color: green}
body|p {color: red}

In this case the text will be red, because now our starting element is body. In other terms: we can attach a given namespace to different elements on a document by specifying their name as the first parameter of the @namespace rule.

jQuery: using CSS3 style properties

As many of you know, the only CSS3 property that jQuery supports natively is opacity. However, we can actually use all other CSS3 properties with the css() method, provided that we use the JavaScript camel-case notation for CSS style properties. For example, given a test element which has only a width, a height and a background color, we can write the following:

$(document).ready(function() {
 
 
 var css3Styles = {
  
  mozBorderRadius: '6px',
  borderRadius: '6px',
  mozBoxShadow: '4px 4px 4px silver',
  webkitBoxShadow: '4px 4px 4px silver',
  boxShadow: '4px 4px 4px silver'
  
 };
 
 $('#test').css(css3Styles);
 
 
}); 

And this is the result:

As you can see, we use both the standard and prefixed property notation using the JavaScript camel-case convention.

jQuery: writing plugin documentation

A jQuery plugin would be useless without a proper and detailed documentation. The key aspect to understand while writing your documentation is to address the most common questions that may come to a user's mind, for example those regarding installation and basic usages. Remember: your approach should always be as simple as you can. First, you should never take anything for granted when it comes to your audience. In fact, your readers may be skilled and advanced web developers who know exactly what they're doing as well as beginners who are simply trying to enhance their web sites some way. A first rule of thumb is: if you feel stupid by reading a plugin documentation, then the documentation itself is badly written. This happened to me when I first tried to use the SyntaxHighlighter library several months ago. I wasn't able to make it work because there was no clear example available in the documentation.

Here are some key aspects to keep in mind:

Include your documentation in the download file

Delivering your documentation online is fine, but from a usability perspective is more useful to include it in your download file. By doing so, a user can consult it and run his/her own tests even when he/she's offline.

Provide a browser support chart

You should test your plugin before delivering it. If you encounter some problems in one or more browsers, inform the user. There's nothing more frustrating than downloading and preparing your plugin only to find out that it doesn't work in the browser X, especially when such browser has to be supported on your site.

Combine code snippets with live examples

It's always useful for a developer to see the code first and then the live example, so he/she can copy and paste this code and see how it works. Never use live examples only, because a user is forced to view the source of your page to understand what's going on.

Include a copy of jQuery in the download file

I generally use the copy hosted by Google's CDN in all my examples, but sometimes I work on a PC that has no connection. So it's preferable to use a local copy of jQuery and include it in your download file.

Simple and advanced examples

You should always break down your examples into simple and advanced. By doing so, you can actually address the needs of those who have only recently downloaded your plugin as well as the needs of more advanced users.

Explain all plugin options carefully

"What happens if I use the option x instead of option y?" asks the user. You should always provide detailed examples for each option included in your plugin, starting from the default ones. Explain all combinations carefully, with full details, providing also live examples.

Provide a minified and normal version

Always minify, not obfuscate. Provide also the non-minified version of your plugin in the download file, so your users can study it and learn from it.

Provide minified and normal CSS files

If your plugin uses CSS and graphics, provide also a minified version of your style sheet, especially when it has reached a certain weight. A non-minified version is useful for changing styles more easily.

Provide graphic templates

Graphics include everything related to images. If you use graphics combined with CSS, it's useful to provide some kind of templates (such as Photoshop PSD files) in order to allow a user to modify the default design.

jQuery: formatting MySQL blog dates

In this post I'm going to show you how to format a MySQL blog date into another format. Generally speaking, this kind of formatting is performed before sending the output to a browser by the CMS itself, so this post has only a demonstrative purpose. MySQL has the following format, called DATETIME:

yyyy-mm-dd hh:mm:ss

We want to turn the above format into this:


<span class="day">dd</span>
<span class="month">mm</span>
<span class="year">yyyy</span>

Let's get started with a basic HTML structure like this:

<div class="post">
 
 <div class="post-title">
  
  <h2>Lorem ipsum dolor</h2>
  
  <p>2010-12-28 17:27:28</p>
  
 </div>
 
</div>

As you can see, the date contained within the paragraph is in the MySQL format. Now we can add jQuery:

$(document).ready(function() {
 
 
 $('div.post-title').each(function() {
  
  var title = $(this);
  var date = title.find('p').text();
  
  // MySQL date: yyyy-mm-dd hh:mm:ss
  
  var rawDate = date.replace(/-+/g, ' ').replace(/:+/g, ' ');
  
  var dateArr = rawDate.split(' ');
  
  var reducedArr = dateArr.slice(0, 3);
  
  var day = reducedArr[2];
  var month = reducedArr[1];
  var year = reducedArr[0];
  
  var html = '<span class="day">' + day + '</span>' +
             '<span class="month">' + month + '</span>' +
       '<span class="year">' + year + '</span>';
       
        title.find('p').html(html);  
 });
 
});

We replace all the '-' and ':' tokens of the paragraph's text with spaces. Then we use those spaces to create an array and we reduce it using the slice() method. So we have all the textual parts we need. Finally, we create the HTML fragment to be inserted in the paragraph itself. You can see the final result here.

jQuery: using namespaces

Sometimes you have to use more than one JavaScript framework. In this case, it's likely that some problems may arise especially when two libraries share the same syntax constructs. For example, both the Prototype and jQuery frameworks use $ as their preferred alias. Though most developers use the jQuery.noConflict() pattern to avoid such conflicts, sometimes it's preferable to wrap the jQuery object with a proper namespace. For example, you can use the namespace created by your own objects and wrap the jQuery object as a property of such objects. Example:

var App = {

   j: jQuery

}

By doing so, the jQuery wrapper is now part of the namespace created by your own application. Later you can use it this way:

App.j(document).ready(function() {
 
 alert('Test');
 
});

By doing so, you avoid any possible conflict. One major drawback of this approach is that you have to access your newly created property every time you want to use a jQuery expression. However, this prevents you from polluting the global namespace using a global variable.

jQuery: retrieving data from a database

Really interesting video that shows you how to retrieve data from a MySQL database using PHP as back-end language and jQuery's AJAX methods on the client side. Some things are not correct if you want to achieve the result of a fully validated document, such as the name attribute used on the search form, but these things can be easily fixed. Really valuable if we compare this video to the paramount amount of inconsistent results that you get from YouTube.

CSS objects

CSS objects are the way by which browsers represent page elements according to the CSS specifications. In this model, each element represents an object that, in turn, has its own attributes. The main attributes of each object are basically two: coordinates and role.

Coordinates

Each object is contained within a rectangular region of the screen along three axes: x, y, and z. The first two axes define the width and height of an object, whereas the z-axis defines it position within a stacking order, for example when elements overlap due to absolute or relative positioning. A browser computes these coordinates using absolute lengths which are later converted according to the rules defined by an author or user style sheet.

Coordinates are mutable. They can vary according to the CSS rules specified in a style sheet but a browser must always know the exact coordinates of each element to perform page calculations, such as those required by the reflow process. For that reason, each browser has its own internal tracking system delegated to one or more components of its own code.

Coordinates are actually effected by CSS rules. More specifically, they're affected by those properties that work together with the CSS box model.

Role

Each object has its own display role defined by the CSS display property. Each role breaks down into two categories: default and user-defined. A default role is the role defined by the default style sheet that a browser uses when there are no styles attached to a document. These roles are:

  • block

    Defines a block object.

  • inline

    Defines an inline object.

  • inline-block

    Defines an inline-block object.

  • table value

    Defines an object that belongs to a table context.

These roles are mutable, although it's not always easy to turn some objects into others (such as table objects). Instead, the roles defined by an external style sheet (both by an author or a user) takes always the precedence over the roles defined in a browser style sheet due to cascade.

Formatting a chat with CSS

In this post I will show you how to format a chat line with CSS. This useful exercise will involve the use of a definition list to mark up our chat that will be later formatted by CSS. The basic markup is as follows:

<dl id="chat">
 
 <dt>
  
  <img src="css-chat/1.jpg" alt="Jane" />
  
 </dt>
 <dd>Hi Joe!</dd>
 
 <dt><img src="css-chat/2.jpg" alt="Joe" /></dt>
 
 <dd>Hi Jane!</dd>
 
 <dt>
  
  <img src="css-chat/1.jpg" alt="Jane" />
  
 </dt>
 <dd>How you doing?</dd>
 
 <dt><img src="css-chat/2.jpg" alt="Joe" /></dt>
 
 <dd>Fine.</dd>
 
 <!-- more chat messages -->
 
</dl>

We have the following elements:

  1. The dt element will contain the chat avatar of each user. Note that each image has a proper alt attribute.
  2. The dd element will contain the actual content of each chat message.

And here's our CSS code:

body {
 
 margin: 0 auto;
 width: 50%;
 padding: 2em 0;
 background: gray;
 color: #333;
 font: 62.5% Arial, Helvetica, sans-serif;
 
}

#chat {
 
 margin: 0;
 padding: 1em;
 background: #fff;
 border: 2px solid silver;
 -moz-border-radius: 6px;
 border-radius: 6px;
 font-size: 1.3em;
 overflow: hidden;
 height: 100%;
}

#chat dt {
 
 float: left;
 width: 110px;
 height: 110px;
 margin-right: 1em;
 clear: left;
 padding-bottom: 0.5em;
 
}

#chat dt img {
 
 display: block;
 width: 100%;
 height: 100%;
 
}

#chat dd {
 
 float: right;
 width: 70%;
 background: #eee;
 margin: 0;
 padding: 0.5em;
 -moz-border-radius: 6px;
 border-radius: 6px;
}

Since we use floating, we also provide a self-clearing mechanism to avoid the overlapping of content. You can see this demo here.

CSS: common web fonts list

It's often useful to have a short list at hand of common web fonts in use on the web. This page summarizes the most used web fonts across various platforms and operating systems. As you can see, this is a good starting point when it comes to provide fallback mechanisms and practices for backward compatibility for font specification. Fonts like Arial, Helvetica, Georgia and Verdana (and many other) are very hand for creating web pages that degrade gracefully when a specified font is not available on the user's system.

CSS: hanging drop cap

In this post I'm going to show you how to develop an hanging drop cap using CSS. A drop cap is usually the first stylized letter of a block of text, for example a paragraph. To achieve the desired effect, we won't use the :first-letter pseudo-element, because at the time of this writing its rendering varies greatly from browser to browser. Instead, we'll use the following markup:

<p class="cap-para"><span class="cap">L</span>orem ipsum dolor...</p>

We'll use contextual positioning to put our first letter just outside its parent paragraph. For doing this, the paragraph itself will need to have some extra padding to host the letter. Here's the CSS code:

p.cap-para {
 
 padding-left: 3em;
 position: relative;
 
}

p.cap-para span.cap {
 
 font: 3em sans-serif;
 padding: 0 4px 0 0;
 position: absolute;
 left: 0.2em;
 top: 0;
 color: gray;
}

We gave an amount of padding which equals the font size of the letter. You can see the final result here.

JavaScript and usability

JavaScript can actually enhance the overall usability of a web document through a series of best practices and patterns. Unlike accessibility, usability is a field where JavaScript can play an important role. The goal of this post is to provide a simple guide to the various aspects of this topic.

AJAX

AJAX, if properly used, can reduce significantly the stress caused by the overused click-wait-reload model. In its essence, AJAX should be used to provide the instant feeling of immediate responsiveness. A user clicks and something immediately happens without page reload. However, there are some best practices to follow:

  1. Always provide a fallback mechanism in the case that an AJAX request doesn't work.
  2. Provide descriptive and user-friendly messages.
  3. Make all page actions self-evident through a proper labeling and styling.

Forms

Forms is a key area when dealing with user interactions. If poorly developed, this kind of interactions can cause frustration in the user. JavaScript can enhance form usability in the following ways:

  1. Instant validation.
  2. Instant user messages.
  3. Progressive display of fields.
  4. Handling of the submit event.
  5. Inline suggestions during typing.

All these features should be carefully developed following these best practices:

  1. Provide descriptive error messages.
  2. Provide descriptive info messages.
  3. Handle keyboard navigation through a proper use of events.
  4. Don't use return false; on form submission, but always use the preventDefault() method of the event object.
  5. Hide only the fields that a user won't fill out.
  6. Use AJAX to provide suggestions during typing. This is especially useful on search forms.

CSS: dynamic form messages

Another chapter of the series "Look, ma! No JavaScript!". In this post I'm going to show you how to create dynamic messages on forms using only CSS. Basically, CSS actually controls one basic aspect of form elements, namely their ability to get focus. So we can take advantage of this aspect in order to create dynamic messages that will be shown only when an element gets focus. The CSS code required to accomplish this task is incredibly simple and is shown below:

#form ul li span.info {
 
 float: left;
 font-weight: bold;
 text-transform: uppercase;
 color: #d40;
 display: none;
 
}

#form ul li input:focus + span {
 
 display: block;
 
}

When a text field gets focus, the message is shown, and when it loses focus, the message is hidden again. You can see this demo here.

JavaScript: cloning objects with prototype

Currently JavaScript provides no native methods to implement the cloning of an object. Cloning an object means having another object whose properties and methods are an exact copy of the original's properties and methods. Although this is considered a bad practice, I'm going to show you how to achieve this by augmenting the prototype object of the native Object class. For example, if we have an object literal like this:

var Class = {
 
 property1: 'Test',
 
 property2: 'Foo',
 
 method: function() {
  
  alert('Baz');
  
 }
  
 
};

We can augment the prototype object of the Object class this way:

// Check first if this method has already been implemented natively.

Object.prototype.clone = function(obj) {

    if(typeof obj === 'object') {
    
    
       obj = new Object();
    
    
       for(var i in this) {
       
          obj.constructor.prototype[i] = this[i];                  
       }
       
       
       return obj;
        
    
    
    } else {
    
    
        throw new Error('clone() works only on objects.');
    
    }
 
};

As you can see, we return a copy of the original object with all its methods and properties by dynamically augmenting its prototype property. Some tests:

var Class2 = {};

Class.clone(Class2);

Class2.method(); // alerts 'Baz'
alert(Class2.property1); // alerts 'Test'

CSS: floats on multiple lines

One of the main characteristics of CSS floats is the computation of space performed by browsers. When there's no more room available on a line, exceeding floats are automatically moved to the next line. And so on. We can take advantage of this fact by implementing a system that, given a stated width for each line, automatically pushes floats on the next line, thus keeping our layout organized. For example, given the following structure:

<div id="container">
 
 <div class="float"></div>
 <div class="float"></div>
 <div class="float"></div>
 <div class="float"></div>
 
</div>

we can write the following CSS code:

#container {
 
 width: 400px;
 overflow: hidden;
 
}

.float {
 
 float: left;
 width: 200px;
 height: 200px;
 
}

Each float is 200 pixels wide, so on each line there will be only two floats. You can see the result below.

Pure CSS tooltips

Continuing the series called "We can do it without jQuery", I could not miss the chance of talking about CSS tooltips. CSS tooltips are an often misunderstood feature that can actually enhance the visual appearance of our pages. In its purest form, a CSS tooltip consist of an hidden span element contained within a link. When a user hovers the aforementioned link, the tooltip appears just below the link. As many of you have already guessed, this is all about contextual and absolute positioning, as we'll see later. We start with this markup:

<a href="#" class="tooltip">amet <span>Lorem ipsum dolor</span></a>

And this is our CSS:

a.tooltip {
 
 position: relative;
 text-decoration: none;
 border-bottom: 1px solid;
}

a.tooltip span {
 
 width: 150px;
 display: none;
 background: #ffffa0;
 color: #000;
 font-size: small;
 padding: 5px;
 border: 1px solid #d40;
 -moz-border-radius: 6px;
 border-radius: 6px;
 
}

a.tooltip:hover span {
 
 display: block;
 position: absolute;
 top: 18px;
 left: 5px;
} 

As you can see, the tooltip is first hidden and then shown when the user hovers the link with his mouse. We've created a new contextual positioning using the declaration position: relative on each link, so that the tooltip will be absolutely positioned just under the link it belongs to. You can see the final result here.

CSS: expanding tabs effect

After all those months devoted to explore the inner depths of jQuery's effects, I actually missed something important. The fact is that sometimes we can actually achieve similar effects only with a little bit of CSS. This is the case of CSS tabbed menus. In this post I'm going to show you how to create a nice animation when a user hovers a tab with his mouse. When this happens, the current tab magically changes its size by gaining an extra height. We start with a markup like this:

<ul id="navigation">
 
 <li><a href="#">Home</a></li>
 <li><a href="#">Articles</a></li>
 <li><a href="#">About</a></li>
 <li><a href="#">Contact</a></li>
 
</ul>

and with very simple styles:

body {
 
 margin: 0;
 padding: 0;
 font: 62.5% Arial, Helvetica, sans-serif;
 background: #fff;
 color: #333;
 
}

#navigation {
 
 height: 2em;
 font-size: 1.3em;
 margin: 1em 0;
 padding: 0 0 0 1em;
 list-style: none;
 border-bottom: 1px solid orangered;
 
}

#navigation li {
 
 float: left;
 height: 100%;
 margin-right: 0.5em;
}

So far we've only horizontally aligned our list items. Notice that the global height of our menu is 2em. Now it's time to stylize the links:

#navigation a {
 
 height: 1.5em;
 line-height: 1.5;
 display: block;
 padding: 0 1em;
 text-decoration: none;
 background: #d40;
 color: #fff;
 font-weight: bold;
 -moz-border-radius: 6px 6px 0 0;
 border-radius: 6px 6px 0 0;
 margin-top: 0.6em;
 
}

#navigation a:hover {
 
 background: orange;
 height: 2em;
 line-height: 2;
 margin-top: 0;
 
}

Did you see the trick? On a normal state, our links have an height which is less than the global height of the menu, plus a top margin that pushes them to the bottom of the menu, right on the bottom border of the whole container itself. To vertically align text we use the line-height property by setting its value on the same value of the height of each link. Then the magic: on hover we add more height and line height to our links so that they're exactly tall as their global container. Since we don't need the top margin anymore, we reset it to 0. You can see the final effect here.

CSS: text justify and letter-spacing

letter-spacing is a useful CSS property that controls the spacing between letters. Generally speaking, this property is used very seldom and only to achieve certain effects on small portions of text (such as headings). However, as Mark Schenk did demonstrate, this property can also be used to control the justification of larger sections of text, such as paragraphs. Combined with the text-align property, we can actually achieve good results, as shown in the following example:

h2 {
 
 font: normal 3em Georgia, serif;
 color: #d40;
 letter-spacing: 0.1em;
 text-transform: uppercase;
 text-align: center;
 margin: 0;
 
}

p {
 
 line-height: 1.4;
 letter-spacing: 0.1em;
 text-align: justify;
} 

And this is the result:

As you can see, the results achieved are good and this proves the benefits of Mark Schenk's intuition.

Skype is down

Apparently Skype seems to have some problems today. Most users are marked as offline and you're unable to see your buddies. On the Skype's site there's a special announcement saying that they're currently investigating the problem. Fortunately this happens when we're about to take our season's holidays, so I don't think this problem will affect our daily work too much. We'll wait and see.

Bad jQuery plugins

In one of my previous posts I've clearly expressed my position on the browser compatibility issue. Anyway, it doesn't mean that something written in jQuery (such as a plugin) is allowed to crash or slow down a browser without any plausible reason. Generally, when we talk about good and bad jQuery plugins we usually consider secondary aspects like code styling and documentation. These are fine features, no doubt about it, but in my opinion a good jQuery plugin should not crash or slow down a browser. Period.

I often see many plugins whose code is pure art and whose documentation is excellent crashing and slowing down Internet Explorer 8 even on local testing. You have to test your plugin before releasing it and you have to test it searching for side effects that may harm a browser. Your costumers don't care too much if your code is fluent and 100% compliant to the jQuery coding standard or if a good documentation is available. These are features for web developers. Instead, test your plugin against any possible malfunction that may cause a browser to crash or slow down. This is of maximum priority in a production environment.

Customizing jQuery UI with CSS selectors

The main problem with jQuery UI themes is that the amount of CSS classes contained in each theme is very significant. Thus, if you want to further customize your theme, you necessarily need to specify your styles using the naming conventions used by jQuery UI. Fortunately, jQuery UI uses a namespace convention that makes each CSS class start with the ui prefix. This is useful when you have to perform a global mass reset on your UI widgets, but it's not recommended due to some evident side effects that will affect the behavior and visual presentation of the widgets themselves.

Further, it's often hard to remember the name of all UI classes. So we're going to use CSS3 attribute selectors to minimize this problem. For example, if you have a basic dialog box like this:

you can use CSS3 attribute selectors to override the default styles of jQuery UI:

[class^="ui"] {

   border-color: orange !important; 

}

[class*="title"] {

    background-color: orangered !important;
    background-image: none !important;
    color: white !important;

}

And this is the result:

Since I didn't remember the full name of the dialog box's title, I used the substring matching attribute selector to select a partial string on that name. Finally, all jQuery UI classes start with ui, so I performed a global reset using a CSS3 attribute selector on this kind of classes. Note how I did use the !important statement to make sure that my custom styles will actually override the default styles of the library.

On the origin of Christmas sadness

I think there's always a logical explanation to all human behaviors and feelings. For example, have you ever experienced a kind of morbid depression during Christmas holidays? In persons affected by a mood disorder this is generally due to the season's transition occurring during December, when the overall amount of daylight is dramatically reduced to its minimum, at least until the end of December. In persons without this kind of problems, social and environmental factors may actually affect their way of living. Generally, the truism about the fact that during Christmas holidays you must be happy because everybody's happy is rooted in the view of life that today most media use as their own Gospel. This view desperately tries to hide the simple and obvious truth about consumerism that so clearly has been expressed by Irvine Welsh in Trainspotting: live, consume, die.

But there are people who think differently: why should I follow this line? why should I be happy only because the media's Gospel tells me that it's Christmas? Why should I buy something new? Why should I consume? And what is at the end of the line? Christmas holidays force this kind of people to face the fact that they're a minority. And they actually feel lonely. And when you feel so, the shadow of sadness silently slips under your door. The solution is to turn this sadness into energy, trying to find if there's actually an end to this line. Finally, these people conclude that there's no line at all. And if you want to, Christmas is every day.

CSS: a menu with transformations

In this post I'm going to show you how to animate a navigation menu using CSS transformations. At the time of this post, browsers support transformations only through vendor prefixes, so we're going to use them. Basically, we have a simple navigation menu like this:

<ul id="navigation">
 
 <li><a href="#">Home</a></li>
 <li><a href="#">Articles</a></li>
 <li><a href="#">About</a></li>
 <li><a href="#">Contact</a></li>
 
</ul>

The first styles attached are very simple:

#navigation {
 
 margin: 1em 0 0 0;
 padding: 0 0 0 1em;
 height: 2em;
 list-style: none;
 border-bottom: 2px solid #000;
 
}

#navigation li {
 
 float: left;
 margin-left: 0.5em;
 height: 100%;
 
}

#navigation a {
 
 height: 100%;
 line-height: 2;
 background: #666;
 border: 1px solid #000;
 border-bottom: none;
 color: #fff;
 display: block;
 text-decoration: none;
 padding: 0 1em;
 text-transform: uppercase;
 font-weight: bold;
 
}

Now we're going to animate the menu items when a user hovers a link with his mouse. Here's the code:

#navigation a:hover {
 
 -moz-transform: rotate(-10deg);
 -webkit-transform: rotate(-10deg);
 -o-transform: rotate(-10deg);
 
} 

As you can see, all menu items will be rotated counterclockwise for 10 degrees. The final effect is very peculiar and you can see it here.

CSS: vendor prefixes and validation

After publishing my first CSS template on CSS Discuss, I got several reactions that outlined the fact that the CSS code used there didn't pass validation due to the presence of vendor prefixes (such as -moz-border-radius and the like). Now I think it's time to talk about the state of the art concerning vendor prefixes and CSS validation. First of all, vendor prefixes are not valid. CSS specifications clearly state that these kind of prefixes cannot be considered as a part of any CSS specifications, thus they're not valid.

However, if you consider validation as an important part of your development process, you need to know what really validation is useful for. Validation is useful only for parsing purposes, not for getting a W3C badge claiming that your site is standard compliant. It needs more than a badge to be standard compliant. Standard compliance requires that your site must be accessible, usable and well-structured from the IA's point of view. Even if your CSS is valid, it doesn't mean that your work is outstanding or even professional.

Validation is a bureaucratic matter. It's absolutely required when you have to conform to some particular state law concerning web sites (like Section 508 in the USA), but nothing more. From a parsing and performance point of view, a vendor specific prefix doesn't affect browsers more than a normal CSS hack (but a vendor prefix is not an hack, of course). Remember that this kind of prefixes are often the only way to get accustomed to new CSS properties as they're currently supported in the newest versions of browsers.

In a nutshell: if you want to stick to CSS badges and bureaucracy, then avoid vendor prefixes. Otherwise, they're not evil.

The rise and fall of Firefox

After four years of predominance in the new trends of browser market, Firefox seems to have exhausted its power of stimulating new users and adopters. In the meantime, we're assisting to the meteoric rise of Chrome among web users. The point is that during all these years Firefox has not been able to develop new strategies for getting more users.

Supporting web standards is not enough: now even the "infamous" Internet Explorer is on the right way to become a full standard compliant browser as of version 9. Using extensions is not enough: despite the fact that these kind of plugins seem to reasonably affect the overall performance, now other browsers start to adopt a similar strategy. Performance is not enough: even if the overall performance of the newest release seems to put Firefox to the level of performance monster like Chrome and Safari, now all other browsers are adopting the same strategy.

In a nutshell: before Chrome, Firefox was the alternate browser, with a capital "t". Now it seems to be just another alternate browser.

jQuery: reflection API functions

jQuery provides several utility functions that can be used to add an extra level of introspection to our code. Among these functions, there are four functions that are particularly useful for implementing a reflection routine on our code. These include:

isArray()

Determines whether the argument is an array.

Example
var Class = {


    collection: [1, 2, 3, 4],
    
    orderCollection: function(arr) {
    
       
       if(!$.isArray(arr)) {
       
       
           throw new Error('orderCollection() accepts only arrays');
       
       }
       
       // other code
    
    
    }


};

isEmptyObject()

Check to see if an object is empty (contains no properties).

Example

var Class = {


   factorize: function() {
   
       var o = {};
       
       return o;
   
   
   },
   
   getInstance: function(obj) {
   
   
       if(!$.isEmptyObject(obj)) {
       
       
           throw new Error('getInstance accepts only empty objects.');
       
       }   
   
   }
   
   // other code


};

isFunction()

Determine if the argument passed is a Javascript function object.

Example
var Class = {

    method: function() {
    
        alert('Test');
    
    },
    
    
    autoload: function() {
    
    
        for(var i in this) {
        
        
            if($.isFunction(this[i]) && this[i] !== arguments.callee) {
            
            
                this[i]();
            
            }
        
        
        }
    
    
    }


};

isPlainObject()

Check to see if an object is a plain object (created using {} or new Object).

Example
var Class = {

    newInstance: function() {
    
    
        var o = new Object();
        
        return o;
    
    },
    
    getInstance: function(obj) {
    
    
        if(!$.isPlainObject(obj)) {
        
        
            throw new Error('getInstance accepts only plain objects.');
        
        }
        
    
    }
    
    // other code


};