Tuesday, May 15, 2007

A Nested Format for CSS Files

As my comfort level with Cascading Style Sheets has increased, I found my CSS files growing in size and complexity. The struggle has been to keep these files organized and easy to maintain. My approach in the past has been to keep my CSS selectors in the following order:

  1. Tags
  2. Classes
  3. IDs
and using alphabetical order within these categories. While it is a method for organization, it is not very good. There is no visual connection between my CSS code and my HTML document, and the format does not lend itself well to optimizing the code.

Last week I stumbled on the Sass framework. Sass is a Ruby library for generating CSS files. While I do not use Ruby so I cannot make use of the framework, one of the output formats intrigued me. This format uses whitespace to give the appearance of one selector being nested inside of another.

Original
table
{
margin: 25px 0 25px 0;
border: 1px solid black
}

thead th
{
text-align: left;
font-size: 1.2em;
}

th.numeric,
td.numeric
{
text-align: right;
}

tbody th
{
text-align: left;
}
Nested
table {
margin: 25px 0 25px 0;
border: 1px solid black; }

table .numeric {
text-align: right; }

table thead {}
table thead th {
text-align: left;
font-size: 1.2em; }

table tbody {}
table tbody th {
text-align: left; }
If you pay attention to the braces you will notice that the selectors are not actually nested, but the whitespace give the illusion that they are. I am still experimenting how explicit to be when nesting the selectors. I like the format because it corresponds to the structure of the related HTML document and makes it easier to see duplicated style rules.

Give this CSS format a try and let me know what you think.

No comments: