How do you format your code?
28 NovI’ve been asked few times how do i format my code. I try to stick to a easy to read and understand style. Sometimes i do, sometimes i don’t. Let’s talk first about those times i do
CSS Code
Each child is indented with a tab. So, i have this style:
1 2 3 4 5 6 7 8 9 | #header { } #search { } #search button { } |
When you read only CSS you know that #header is the parent, #search is his child and the parent for button. Easy to read, easy to understand, right?
I try to avoid code like:
#parent #another_parent #header #search button { }
Because is kinda bogus.
I saw some guys who wrote their code on single line, without any indentation. Even if you have a less KB file, the result is hard to read and edit. Even though, i use very rarely one line code when i have to add one-two rule to a selector ( something like .element { color:red } ).
HTML Code
Actually… Somehow, i have same rule here: every child have a one tab indent:
1 2 3 4 5 | <div id="header"> <form action="" method="get" class="search"> <button type="submit">Button</button> </form><!--/.search--> </div><!-- /header--> |
As an extra info: when i have large blocks of code (div, forms), on closing tag i add a comment with the id or class name: if the block has a class, the closing comment is /.class name and if is an id /id name
Again, easy to read and to maintain, especially when you reuse some of your code.
Javascript/jQuery Code
Well.. Probably is already clear enough how do i do:
1 2 3 4 5 6 7 8 9 10 11 | function function_name() { var someVar = 1; if( someVar === 1 ) { alert('someVar is 1!'); for(i=0;i<10;i++){ alert(i); } } else { alert(':('); } };//function_name |
Conclusion
The main keywords are: indent and comments. You don’t have to overuse indent, because the code will be impossible/hard to read. Also, don’t over-comment your code. Don’t comment the obvious :
var foo = 'bar'; // the 'foo' get 'bar' value
Well.. I can’t say nothing else but „happy coding!”.

