I’m never sure what the best (most efficient) way to select an element is.
Lets say I have the following layout (extremely simple example)
<div id="navigation">
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
</div>
- I want to select my unordered list (ensuring I don’t affect any other UL’s throughout my site), should I do
#navigation ul {}or assign a class to the UL? - I want to select my list items, again ensuring I only affect those. Should I do
navigation ul li{}or assign a class? - And finally, If I want to select my first link and style it, should I do
#navigation ul li:first-child {}or assign a class?
I appreciate these questions are pretty much the same, but I’m curious when you should use a class and when not to.
There’s no hard and fast answer here.
A general rule of thumb might be to use classes when you want to group certain elements together, treat them the same and using a class is the only means of doing it.
In your last example for instance, there is strictly no need for a class.
But, using a class in example 3 will result in better performance, as the browser will located the relevant items quicker. Traded off against this is a slight reduction in code-legibility..
If you have class names on everything then it becomes harder to read the rest of the markup.
In short, in what you have shown above, what you have written is fine imo.
You should read this article though which covers selector efficiency.
Basically the order of efficiency is as follows:
The performance difference between classes and Id’s is normally irrelevant.
Going further down the list though, things slow down considerably.
This isn’t an argument to add classes and id’s everywhere – it just allows you to judge the trade-off between performance and maintainability.