Tuesday, July 14, 2009

CSS Syntax Formatting Standards

Designing for readability is very important. Not only can it cut down on your own development time when you perform maintenance or make improvements to older sections of your site that you haven't seen in a while, but it also makes it much easier for other developers to read your code.

Before we get into standards its important to note that tabbing, comments, and spacing increase the file size of your style sheets. Before you implement these kinds of standards, ensure you have some kind of compression in place (I recommend Minify for both CSS and JS) to keep the file size under control. Minify is extremely important for shared hosts such as HostGator that do not permit gZip compression.

Tabbing
Always tab/nest your code accordingly. Below is a code snipplet from some CSS on one of our main templates. Notice it's easier to read when it's tabbed as you can quickly determine which elements are children of which. In a larger stylesheet this really helps because you can see #hd .nav and know that's not what you need and skip down to the next section.

#hd .nav {
  border-color: #223f4a;
  border-style: solid;
  border-width: 1px 1px 0 1px;
 }
  #hd .nav ul {
   margin-left: 98px;
  }
   #hd .nav ul li {
    float: left;
    margin: 2px 0 6px 0;
    padding-right: 2px;
    position: relative;
   }
CSS Selectors
Using the same snipplet above, you'll notice that our CSS Selector's anchor is unique and not a class. When available, use a unique anchor rather than a class. This will help prevent CSS from effecting elements it was not intended to effect.

Also notice that within our selector, while the 3rd child could very easily be called #hd li instead of #hd .nav ul li, because of our tabbing and to increase readability we generally include tree elements in the selectors. This will also ensure that it only effects exactly what it was intended to effect rather than effecting any other lists.

Selectors by Class
In your CSS selectors it's better practice to use classes rather than elements.  For instance, the below example is restricted to a ul element and cannot be used on a ol element.  As more useful tags are being included with CSS, get in the habit of designing your code for flexability, you'll be surprised at the different ways you utilize the same CSS across multiple elements.

ul.bullet {
 background-image: url(resource/bullet.gif);
 background-position: 4px 6px;
}

No comments:

Post a Comment