CSS code formatting, improve readability

It is not a secret it is a fact. Structure your code will always be useful. If you work in a team or if you often re-open old projects you will see that having a well structured file decrease considerably the effort needed to maintain and understand the document.

There is some “standards” used in html or php or any other scripting language but not really in CSS.

In the young age of CSS we were writing ten lines of code just to get the color and the font size sorted. No need for formatting here. Know, with all the buzz about standards compliant sites and good practice it’s not rare to see a six hundred lines CSS file.

Personally I use some simple guide line:

Indent your code!

Well this one is pretty common to any programing language. Indent your code!. Sorry just to say it again. Code indentation is the best way to transform a messy document into some hierarchic, structured code.

For example:

h1{ font-size:1.8em; color:red ; border-bottom:1px solid #000; }
div.wrap{ width:940px; margin:auto; }
#leftCol { width:600px; float:left; }
#right { width: 320px; float:right;}

Becomes:
h1
{
 font-size:1.8em;
 color:red;
 border-bottom:1px solid #000;
}

div.wrap
{
 width:940px;
 margin:auto
}

 #leftCol
 {
  width:600px;
  float:left;
 }

 #rightCol
 {
  width: 320px;
  float:right;
 }

Isn’t it better? Indentation for each CSS definition but also indentation when an element is inside the previous one. Here I suppose I have a wrap div and inside two div’s: #left and #right. Those two are indented because they are children of the wrap div.

Order the properties by appearance:

The second rule I use is also very simple. Order the element by their appearance in the html related. For example, every footer style are at the end of the file, because the footer is also at the end of my html. Header style at the top and so on. General properties like h1, h2, a, p, body, etc are appearing before any other because they are general properties.

That pretty much it for me, but if you want to read more about other technique I recommend Improving Code Readability With CSS Styleguides from Smashing Magazine.

Leave a reply