Creating Effective Web Applications

Weblog

Structuring CSS Files

30 03 2007, Michiel van Vlaardingen

At MovingLabs we always try to use semantically correct XHTML combined with elegant CSS stylesheets. We like to have a clear overview of things and therefore try to minimize the amount of code. Our XHTML often directly reflects the hierarchical structure of the content. We demand a similar structure for the layout however CSS being a rule based system does not support hierarchical structures by nature. This could lead to cluttered source files.

An example

<div class="container">
<h1>My site</h1>
<div class="news">
<h2>Nieuws bericht</h2>
<p>content...</p>
</div>
</div>

This XHTML structure would go with a CSS file like this:

.container {border: 1px solid black;}
.container h1{ color: red; }

.news {border-top: 1px solid black;}
.news h2{color: blue}
.news p{ font-weight: bold;}

There is a clear relation between XHTML and CSS, but with large stylesheets it can become unclear what should go where and what inherits or overrules what. Therefore we use the following convention for layout of the CSS files:

.container{
border: 1px solid black;
}
.container h1{
color: red;
}

.news {
border-top: 1px solid black;
}
.news h2{
color: blue
}
.news p{
font-weight: bold;
}

The whitespace does not have a semantic meaning but it makes the file more readable. Furthermore this structure gives any rule a single intuitive location in our file. Using this structuring helped us reduce the amount of properties we used because it's now immediately clear what properties are redundant.

Besides this hierarchical structure we also favor grouping similar properties on a single line:

.container{
position: absolute; left: 0px; top: 0px;
margin: 5px; padding: 10px;
font-size: 15px; font-weight: bold;
}

Grouping them allows to have a clear structure without taking up all those lines which makes it hard to see the hierarchical structure we are in.

Applying these conventions reduced the size of the stylesheets, the time we spent on making them and even more the time we needed to maintain them

This is a translation of an article by me on my dutch weblog published on 13-03-2006.



05 07 2015: Export Excel files
17 03 2011: Brand New Observu Coming
14 12 2010: Print Details

 

RSS