Site Moved

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


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 -

.green-text {

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 {
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 {

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.


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,

body {
a {

div#header {

/*Navigation Bar*/
div#navigation {

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.


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 {

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 {

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 {
    border:1px solid black;
p {
div.header a {

  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;


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

body {
a {

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 {
ul#menu_bar li {
    background:url(bullet.gif) no-repeat left;
ul#menu_bar li a {

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.

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 {

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 {
    border-bottom:1px dashed black;

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

a {
a:hover {


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 {
.box-simpler {
    border:1px dashed blue;


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 {
    voice-family: "\"}\""; /*Box Model Hack*/

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.


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


Advanced JavaScript Tutorial

Finally! The end is here. You have no idea how long I have waited to tell that. I completed the Basic JavaScript Tutorial in January 2005. I thought that I would finish the Advanced JavaScript Tutorial by February - it got extended. The next deadline was at April - again no luck. As Douglas Adams once said...

I love deadlines. I especially like the whooshing sound they make as they go flying by.

But finally in August I managed it - I have completed the tutorial. It did not quite reach upto my original expectations, but it is still one good tutorial - atleast in my compleatly unbiased opinion. ;-)


Onan Holidays

Finally some free time. The Onam holidays have started - which means that I will be free for the next four days. Not much - but I have a lot of planes for that - stuff to write, programs to code, languages to learn.

As a result of this, I finally got the time to take Sudoku out of the Beta stage. Now I am writing a Sudoku solver in ruby. It is almost finished - just some more features to add.

Filed Under...


Learning Ruby

As of today, I officially 'know' Ruby. If you are not familiar with Ruby, it is a programming language that claims to be as easy to use as Perl and as Object Oriented as Python. I am learning this language right now. I have written a couple of programs in Ruby - so now I know ruby - at least the basics of it.

I have heard about ruby for a long time now - but till now I did not have the motivation to learn it. But then came the 'Ruby on Rails' framework for web development. And since I am in web development field, this is almost impossible to ignore. As a result here I am, trying to learn ruby.

I find learning ruby very easy. I already know many other languages and am proficient in three other main scripting languages(perl,php and tcl). So I got hang of the language rather easily. All you have to do is connect something in this language to something in a language you already know. For example, the if loop in ruby is like this...

if a == 5 then
    print "A is Five"
The same for perl is...
if ($a == 5) {
    print "A is Five";

After this connection is made, there is no more problems. All you have to do is make the connection for every thing in the language. This is very easy to do - just read some ruby scripts and within minutes you will get the hang of it.

The problem comes where there is something new in the language - something that is not there in the language what we already know. For example, in ruby every thing is an object - ruby has no primitive types. So a string is an object as is an integer. As a result, the perl code will not connect with the ruby code as shown by the following example.

#Perl - Finding the length of a string.
my $hello = "Hello World";
my $length = length($hello);
print "The number of '$hello' is : $length";

And the ruby code for the same is...

hello = "Hello World"
print "The number of chars in ",hello," is ",hello.length

The perl code calls a function with the string as the argument and it returns the number of chars in the string. But in ruby, the length is a property of the string variable. I solved this problem by making the connection with javascript. The example is...

var hello = "Hello World"
alert("The number of chars in "+hello+" is "+hello.length)

In javascript(as is in java), the connection is made perfectly. The hello.replace(/l/g,"L") in javascript becomes hello.gsub(/l/g,"L") in ruby. Everything is an object - yeah, I think I got that.

The next problem arises when there is a feature in ruby that is not in any language you know. For example, we will print every element of an array.

#Ruby code...
an_array = ["Julius Ceaser","Alexander","Binny"]
an_array.each { |name|
 print "This Item : " + name + "\n"

Yes, I know that the foreach loop in perl can do it - but this is different. A method of the object not only returns the values but it also acts like a foreach loop. If I knew the Smalltalk language, this would not be a problem as this syntax is taken from that language - but I don't know that language. I had to struggle with that concept for a few minutes - but after that there was no problems. Many other stuff in ruby uses the same principle. For example, the code for reading the data from a file is given below.

#Open File for reading
aFile ="FileName.txt", "r")

#Process each line
aFile.each_line { |line|
 print line

Here, a line from the file is printed per iteration of the 'each_line' loop. There are many other examples, but after you get the concept of one, the rest will be easy to understand.

Another problem is that numbers and strings are not interchangeable. This one still gives me hell.

# Perl code
my $strnum = "Forty Two";
my $num = 42;
print "In perl, " . $strnum . " is " . $num . ".";

The numbers will be concatenated to the string to be printed. No problems here. But when we come to ruby...

strnum = "Forty Two"
num = 42
print "In Ruby, " + strnum + " is " + num.to_s + "."

NOTE: In Ruby the concatenation operator is '+' and not '.'.

See the code num.to_s? That means that the 'num' variable is to be converted to a string type before printing. If we try the normal route, we will get an error - like this...

print "In Ruby, " + strnum + " is " + num + "."

Temp.rb:3:in `+': cannot convert Fixnum into String (TypeError)

I still can't come to terms with this issue. I understand it, but can't bring myself to appending a '.to_s' at the end of every integer. I try to get over the problem with this code...

print "In Ruby, ",strnum," is ",num,"."

Give me some more time and I will append '.to_s' at the end - but presently, I just can't do it.

Ruby Resources



Filed Under...


Yet Another Strike

Even before the ink dried on the posts about the recent two strikes, we had yet another strike today. Not just a bus strike - we had a motor strike. That means no buses, no taxis, no parallel transport - no nothing. Well, actually there would be private vehicles - but nothing the general public could use to get to their destinations.

If you are waiting for another tale of bravado about how I hung on to a vehicle by my fingertips to get to work, you are wasting your time. After the last experience I have no desire to risk life and limp to get to work - I just took leave from work today.

The strike was called because there was a hike in petrol and diesel prices. I must say that I am impressed with the strikers - I have no memory of three strikes striking so close to each other - with a different reasons for each. But then again, when the strikers decide to strike, who says they need a reason to do so?

Filed Under...


Fixed a bug in Sudoku

I just finished the latest version of Sudoku - 1.03.A - and guess what - it has a (stupid) bug. It did not show up when I was coding it. It did not make its appearance when I tested the script locally. I did not find it after I uploaded it and tested it online. But when the visitors came, it was on the monitor beaming proudly at the user.

I got a lot of feedback from the users about the problem - and I fixed it right away. I could not believe my eyes when I found the bug - two 'g' characters was missing. That's all. And I had to debug the script for an hour before finding this stupid bug... Idiotic script... Foolish Javascript... Moronic Sudoku... (Inaudible inane mumbling)

Filed Under...


More Small Posts

Till now I was laboring under the impression that my blog posts must have sizable content if it was to make an impression among the readers. But while reading the "Your Web Presence" booklet, I came across the following statement.

The average person reads 200 words per minute - the speed reading record is 1347 wpm. In 96 seconds they(your visitors) will read 320 words. So keep thing short and to the point. This may sound crazy but these stats show that longer posts are often largely ignored.

If you look at my earlier posts, you will see that they are somewhat large. So from now, you will get smaller but more frequent posts - atleast that is my aim.


Digit's "Your Web Presence"

I just got this month's Digit issue. If you are not familiar with Digit, it is a computer magazine that I subscribe to. Like always, the "Fast Track" booklet that came with it was just superb. This months issue - "Your Web Presence" is about establishing your identity on the web. From the Introduction...

What is web presence? Is it just acquiring an email address? Is it putting up a site? Is it your online conduct? As a matter of fact, it's all of these things and much more. It's almost like creating your identity online, like in the offline world.

Every thing from hosting a web site to blogs to netiquettes was covered in the book. I read the full book in one sitting. It has good, solid content with relevant illustrations - which are printed very, very badly. But I will NOT complain about that - I read the book for information - not for the pictures.

This might sound blasphemous to regular readers of Digit - but I think that Fast Track is a better book than the magazine itself.

Filed Under...


Subscribe to : Posts