I've just read Scalable and Modular Architecture for CSS and it's got me thinking about a few things. Snook's two principle tennets are:
- Increase the semantic value of a section of HTML and content
- Decrease the expectation of a specific HTML structure
So this means using semantic class names rather than relying on unsemantic element types for targeting. For example rather than targeting .someClass h5
, I might target .someClass-title
instead so that if the h5 is swapped out for something else, things don't break.
Personally I find encoding an element's hierarchy in its name kind of unpleasant (even if it is semantically correct). I would prefer doing .someClass .title
. But to use a class as generic as title you need to accept that this class will be used in lots of different contexts.
So is there anything wrong with using the same class in completely different contexts if I know it will be namespaced by a previous item in the selector?
For example say I have three different places in my site where a class of 'title' makes sense:
HTML
<header class="pageHeader">
<h1 class="title">Some Title</h1>
</header>
...
<article class="leadArticle>
<h3 class="title">Some Article Title</h3>
</article>
...
<ul class="productPreviews">
<li class="product">
<h5 class="title">Some Product Name</h5>
</li>
</ul>
CSS
.pageHeader .title
{
}
.leadArticle .title
{
}
.productPreview .product .title
{
}
Edit: as Alohci mentions in his answer below, a header tag isn't unsemantic, so perhaps this wasn't the best example to use.
Obviously I might be doing something completely different to the title in these contexts, but title makes absolute sense with it's module's namespace, and I never have any intention of using title as a general selector.
This seems to tick all the boxes. It is semantically rich, completely decoupled from implementation. For example if the last example was changed into an ol or a stack of divs, nothing would break, and if title was wrapped in a div it would still be targeted.
This makes sense to me, but I haven't seen this approach used much and I'm wondering why. An obvious disadvantage is that you are chaining classes in the selector, but I think this is preferable to namespacing each classname.