At work we have a lot of css files. 79 to be exact. The code itself is organized pretty well and I am very happy with that aspect of it. There is however one thing that I hate. That is just about any use of id’s as a css selector.
Current wisdom suggests you should use class names for elements on the page that are repeated and IDs where an element has only one instance. At first glance and on a small scale that make sense. On a large scale and after a close look problems start to arise.
Here is a sample of what I wanted to write:
.my-class p {}
But I ran into an issue because at a higher level the in that container was already specified as:
#some-class .some-other-class p
The problem is that ID’s have a high level of inheritance and cannot be overridden without the use of !important or the same or higher level of specificity The solution is simple but makes my code look terrible. So now I have:
my-class { }
.my-class a { }
#some-class .some-other-class .my-class p { }
.my-class .date { }
After I figured this out I started to wonder.. “What is the value of using and ID vs a class name?” Does it make your website faster? Better? More valid? What should I even consider? What would happen if I used class names exclusively for css, and ID’s specifically for javascript? Here are two reasons why I think you should:
1. One of the goals for an modern web developer is to completely separate the 3 main aspects of his/her code. Specifically the structure, presentation and behavior. However anyone who does this using a mix of ID an class names has unknowingly created a dependancy between their behavior and their presentation layer. That means that changing an Id or class name in the css has the potential to break javascript or vise versa.
2. If all css selectors are written with class names, no one style has inheritance over any other rule. The style sheet cascades as it was designed
Overkill? Perhaps, but food for thought.
Good post, with good points.
A system that is easier to debug and maintain wins.
Paul Hepworth
April 28th, 2008