It's considered pretty bad practice to use a class selector in CSS as a single instance, for instance, you would not choose to the name the main_container
element .main_container
, would you? Or would you?
Well actually, I was thinking about this today, and I've come to the conclusion that yes, maybe you would. That's because of the DOM buzz word specificity.
Any CSS developer who has been using it for a while will know that the ID selector (#
) is more powerful than the class selector (.
), but do you know how much more powerful it is? Well 10 times to be exact. For more information on this, read the linked article.
It's important to note that throwing in an ID selector makes it very difficult to overwrite, so using one is not always the best way to achieve something. For instance, say you wanted all the anchor elements inside your main body section to be displayed with a style where you've got the code such as:
<div id="main_container"> <a>Test</a> <a class="tester">Test</a> </div> <div id="sidebar"> <a class="tester">Test</a> </div> </div>
The anchors could simply be selected using the #main_container a
selection. But this means, according to specificity rules, that the anchor would have 101 points (100 + 1), meaning overwriting this anchor with a class is not easy and would require the ID at all costs. Now you want to style the links with the class tester
too, but across the whole site. So we have two choices, either rewrite the page so that the body has an ID too, or, create a selector like #main_container a.tester, #sidebar a.tester
.
Both of these solutions are inadequate.
The single use class
Let's rewrite the HTML and CSS. Add the class singleton
to the main_container
:
<div id="main_container" class="singleton"> <a>Test</a> <a class="tester">Test</a> </div> <div id="sidebar"> <a class="tester">Test</a> </div> </div>
Now our selection can be much weaker, albeit less specific (but since singleton
will only occur once and only once we do not care). We can now select using .singleton a
. We have reduced the specificity to 11 (10 + 1). To overwrite it, we can now just use a.tester
since this also has a specificity of 11 (1 + 10). However, this will only work if it is placed in the CSS file after the reference to the original tag (i.e. after the .singleton a
).
So there you have it, a way to use the class selector as a single instance effectively.