CSS Organisation – Grouping Selectors

In the previous post in this short series on CSS I wrote about splitting CSS files into sections. Whilst this is a simple technique, the choice of how to group is more difficult though, sometimes the most obvious groupings into different areas of the page will lead to duplicating rule sets where the selectors could have been combined. For example you may end up with the following:

We could of course combine these as this:

This definitely appears to be better as we are no longer repeating ourselves and means that should we want to change the colour of these headings then it only needs changing in one place. This no longer fits into either of our sections above but we could just introduce a HEADINGS section.

Whether this is more or less important than the clear grouping is really a matter of personal preference and some pragmatism. It makes sense to avoid repeating yourself but ending up with a lot of single rule declarations with a lot of selectors for each can be much less readable than grouping all the rules for each selector together. This shows rules for three different selectors grouped by the selector.

There is however some repetition of rules so you may feel that this not the optimum way to write these rules. Trying to eliminate this altogether is not the best policy though, in my opinion, as it would leave you with this:

Whilst the repetition is removed it is now, I think, less readable. Admittedly if you want to change the text colour for #intro and #footer then it only needs doing it one place, however, if you need to change only the colour for #intro then quite a few changes are needed.

The main disadvantage to this approach though is that it makes difficult to group the rule sets into effective sections making the overall file more difficult to organise. In the example I have had to group them altogether as rules for paragraphs, this means that these rules have been separated away from the others for that section of the page e.g. the footer paragraph rules are no longer with the footer headings rules.

My personal preference I think would be to pull out the rule for the width only as this appears for all of the selectors is most likely for the value to be changed for all of the selectors if it is changed. This would leave you with the following:

This is a good compromise between the two previous examples. Whilst there may be some additional steps when changes are needed compared to the second example, the increased readability outweighs this.