Site Moved

This site has been moved to a new location - Bin-Blog. All new post will appear at the new location.

Bin-Blog

CSS Coding Style

CSS Style coding style(CSCS). Has a nice ring to it. Other than poetry, I am trying to make a coding style for writing CSS code. Before beginning, I would like to warn you that there is very little use in having a rigid coding style for CSS. CSS or Cascading Style Sheets, as you are well aware, is not a programming language. It is not a cryptic, human unreadable, only-machine understandable piece of text. The CSS code is very transparent and is very difficult to obfuscate - yes, I know that it could be done with a lot of shorthand and source compression, but still will be (relatively) readable.

So what is the use for a coding style for CSS?

Readability - which is more easy to understand -
.class32{color:green;font-weight:bold;background-color:gold;}
OR

.green-text {
    color:green;
    font-weight:bold;
    background-color:gold;
}

I don't have to tell you the effect on readability when a big CSS file is created with the first style of coding - it will be impossible to find anything without wading thru the code for some time. On the other hand, the same task will be a piece of cake if the code is in the second form.

Good Habit - I know many programming languages - and have learned the hard way the necessity for coding in a good style. I find it almost impossible to write very bad code in one language and then suddenly switch to a good coding style in another. So no matter what language you are using, be it perl, python or CSS, write in in a good style. If you have to code, why not do it in a good way?

Structure - A good code will have a easier to understand structure that can be understood at a single glance - this is especially true for CSS. In programming languages, the indentation can be used to visually show the structure - which block is in which block etc. In CSS .green-text { color:green; } says nothing about where it the element is located - but

DIV#main-contents P.text SPAN.green-text {
    color:green;
}
shows exactly where the element is located in.

I will keep in mind three things while creating this style guide -

  • Functionality - The code made with this style must work - not very hard.
  • Readability - The code must be easy to read.
  • Small size - The resulting file must have not have unwanted stuff - the file size must be as small as possible.
Another thing before we start - the below rules are not rigid laws. As Morpheus said "some can be bend - others broken". If you feel that any particular rule is not a very good one, feel free to rewrite it. Also note that these rules are written by me to act as guidelines for me as well as for you - if you take a look at my other site's CSS sheets, you will not that I have used bad coding style. I am hoping that this article will force me to employ a better style - at least from now on.

CSS Definition Types

Enough philosophy - let us get to the subject at hand - CSS Coding style. There are three different types of CSS definitions.

Inline styles

The styles that are defined in the tag itself. Example... <span style="color:green;">I am green<span>

The rule number one about this - avoid it. Don't use this type of definition unless you are forced to do so with a colt .45 held against your temple. The most important advantage of using CSS is the separation of design(CSS) from content(HTML). If you define the appearance at the appearance level, how can it be any different from (gasp) font tags.

I must admit that I have used this method of definition - it is very hard to resist the temptation to use this style when its late and you want to go home and your boss is breathing down you neck asking every other minute why the project is not complete. I think it is OK to use this style IF and only if that appearance is necessary only in this part of the project and no where else. Still it is not recommended.

InPage styles

I am calling this item InPage style for the lack of a better term. This is the CSS code that is given in the <style> - </style> block - in the head area of the HTML file. An example is given below...

<style type="text/css">
<!--
.green-text {
    color:green;
}
-->
</style>

When using this, remember that you will not be able to change the appearance the page without editing the page - if you are using the external CSS file, you can change the appearance of all the pages linking to the CSS file without editing those page. So using the external CSS file method is more recommended than using the InPage method. If you have to use this style, just keep in mind that you should not use this method when the same styles must be applied for elements in other pages. If the elements are limited to just one file, you may use it.

External CSS file

The best method - using external CSS files. You can link to these files from within your HTML page using the code <link rel="stylesheet" href="style_sheet.css" type="text/css"> where 'style_sheet.css' is the name of the CSS file. This method is the best because...

  • The design is separated from the content.
  • The browser will load the CSS file only once. If multiple pages linking to the same CSS file are viewed, the browser will load the CSS file from its cache and use it. This will save your precious bandwidth.
  • Changing one file can change the appearance of the whole site.
  • Etc.
The rest of this article deals with the rules applicable to this kind of coding.

The X commandments of CSS coding style.

Comments

As I said earlier, CSS is NOT a programming language - so comments are not very necessary. In CSS I would recommend that you avoid comments - save some bytes of bandwidth. Wow! Avoid comment - I never thought that I would say that - if you had seen some of the code that I had the misfortune of editing, you also would be surprised. But all those codes were in programming languages - and those rules don't apply for CSS. I use comments in CSS only for separating different areas of the code. For example,

/*General*/
body {
    margin:0;
}
a {
    text-decoration:none;
}
...

/*Header*/
div#header {
    width:100%;
}
...

/*Navigation Bar*/
div#navigation {
    float:left;
    width:20%;
}
...

The different sections are clearly labeled - using the minimum amount of chars - I did not use /**************** Header ***********/ because I want to make the file size of the CSS file as low as possible. But if that is not a concern for you, use it - it is much prettier that way. Another area where comments are necessary is when you are using CSS hacks - but more about that later.

Case

Simple rule - lower case - all the time. I used to have a uppercase for HTML elements policy - TABLE#root { ... }. But I am dumping it in anticipation of the XHTML standard. In XHTML, all the elements must be in the lower case - so the CSS definitions should also be in lowercase.

Naming Conventions

This is where stuff gets controversial - so I will not give you a straight-forward rule. I will give you all the possible different styles and provide my recommendations - I will leave the choice to you.

Name Separator
Name separator is the method we use to divide the ID/Class name of a CSS rule. For example a class 'left-menu-links' is three words using the separator '-'. We have three different kind of name separators -

Hyphen(-) - Example left-menu-links. This will visually separate the words - and will confirm to the CSS language style. CSS defections use this separator ie. font-weight or text-align. I use this style.

Underscore(_) - Example left_menu_links. Very visual separation of the words. This is the most commonly used variable word separator for programming languages.

Hungarian Notation - Example aLeftMenuLinks('a' stands for anchor). The ability to use prefixes will allow more information in the name - use your imagination for creating the prefixes - 'a' stands for anchor, 'i' for image, 'p' for paragraph and so on. Also this eliminates using an extra character as the separator - again reducing the size. A notable disadvantage is that there is no visual separation of the words.

Name type
The two main choices are...
Name based of Appearance
This style will name the elements based on how they will appear. Example...

.bright-red {
    color:blue;
    font-weight:bold;
}

The advantage of this method is that one can say how an element will appear by just looking at the HTML code. For example, when you see the code
<span class="bright-red">Hello World</span>
you instantly know its color. The problems with this form of usage comes when you have to change the appearance. Image this scenario - you have designed this great looking site and the work is almost over. All of a sudden the client has a idea that all the headings of the site will look better in a blue color. Now you can change the style sheet so that the site uses blue color for its heading. So now the code looks like this...

.bright-red {
    color:blue;
    font-weight:bold;
}

After this, when anyone uses the code <span class="bright-red">Hello World</span>, they will find the 'Hello World' text has a blue color. Another alternative is that you can change the name of the class 'bright-red' to a more meaningful 'bright-blue' - but then you will have to change every instance of 'bright-red' to 'bright-blue' - in every single page of the site!

Name based on Functionality
A more practical approach in my opinion. Here, the name of the class will be 'main-text' - the name will depend on how the class will be used rather than on its appearance. In this case the advantage and disadvantage is the opposite of the appearance based naming - you have to look at both the HTML markup and the CSS style sheet to know how the element will be rendered - but it is change friendly. I use this method when giving name to a class or id.

Indentation and white space

The rule of the thumb here is - enough to make the code look pretty - but not enough to increase the size of the style sheet. I am recommending the following style...

#sidebar {
    width:20%;
    float:right;
    border:1px solid black;
    text-align:right;
    background-color:#bbcaf3;
}
.content,
.text,
p {
    color:#000;
    text-align:justify;
}
div.header a {
    color:red;
    text-decoration:none;
}

  1. No space before the selector(the selector must touch the left margin).
  2. A single space between the selector name and the '{' - #sidebar {.
  3. A tab character before the beginning of the rule.
  4. No space before and after the colon separating the property and value - (color:red;).
  5. Each rule separated by a new line character.
  6. All the grouped selectors(.content/.text/p) must be separated by a new line.

This can be made more beautiful - but that would increase the size of the file. A prettier version of the above code...

/* The bar at the right side */
#sidebar {
    width            : 20%;
    float            : right;
    border           : 1px solid black;
    text-align       : right;
    background-color : #bbcaf3;
}
...

Selectors

Simple
Try to place the element only simple selectors at the top of the stylesheet - for example...

body {
    margin:0;
}
a {
    color:blue;
    text-decoration:none;
}

Context
A selector that matches elements based on their position in the document structure is known as a contextual selector. A contextual selector consists of several simple selectors. E.g., the contextual selector 'p.second-para a' consists of two simple selectors, 'p.second-para' and 'a'.

Place all contextual selectors of a particular element together. For example...

ul#menu_bar {
    list-style:none;
    padding-left:0px;
    margin-left:0px;
}
ul#menu_bar li {
    background:url(bullet.gif) no-repeat left;
}
ul#menu_bar li a {
    color:#208008;
    text-decoration:none;
}

I try to use as much contextual selectors as possible when setting the layout of the page. I think that using it gives the code more structure than using classes and ids.

Class
Perhaps the favorite among all the selectors. Classes must be used to style several elements in the same way. Example... <a href="#" class="link">Hello World</a>

.link {
    text-decoration:none;
}

ID
IDs are to be used if there is only one instance of that element on a page. For example...
<div id="header"></div>

div#header {
    width:100%;
    border-bottom:1px dashed black;
}

Pseudo-elements
Group the rules for an element and its pseudo-elements together. A simple example will make this clear...

a {
    color:blue;
    text-decoration:none;
}
a:hover {
    color:red;
    text-decoration:underline;
}

Shorthand

Many properties can be compress to just one property using the shorthand properties like 'background','font','border',etc. Using this will save a lot of space - but readability will suffer slightly. However I recommend that you use the shorthand method whenever possible.

.box {
    border-width:1px;
    border-color:blue;
    border-style:dashed;
}
.box-simpler {
    border:1px dashed blue;
}

Hacks

There is only one rule about hacks - avoid it like plague. Read the article 'Keep CSS Simple' to know why. But if you want to use a hack even after my warnings, go ahead - but please comment the section and tell others that you are using a hack.

div.content {
    width:400px;
    voice-family: "\"}\""; /*Box Model Hack*/
    voice-family:inherit;
    width:300px;
}

Other Rules

File Naming : Give the CSS files descriptive names - like 'sitemap.css'. If you have some code that will break on older browsers, put it in another file and import it using the @import url(file.css); command. Only new browsers will use that file - thus saving older browsers from themselves.

CSS : Please restrict yourselves to using Level 1 CSS - unless you are the author of some experimental CSS sites like CSS/edge.

Conclusion

I don't care which style you prefer - but please be consistent - pick a style and use that style till the end of your life. Don't use one style for one CSS file and an entirely different one for the next. Happy CSS Coding!

Related Sites

2 Comments:

Anonymous said...

Thanks. This is very useful. I will implement these ideas in my own css coding.

monu said...

:)

u seems to be an usthad in CSS and all :)