Too many web developers decide CSS class names based on what style the class is representing. This is wrong, and should be avoided! Let me explain why.
Consider the following:
<div class="margined">
<div class="float_left">
<div class="bold">Joe Schmidt</div>
<div class="small">23 years old</div>
</div>
<div class="float_left">
<div class="bold">Johnny Bravo</div>
<div class="small">25 years old</div>
</div>
</div>
This is awful! The first reason is that you’re tightly coupling style and markup. Suppose, you wanted to change the look of the user name, you’ve both have edit your markup and you stylesheets. Second, what if you suddenly needed to apply some behavior through javascript when hovering the age element? You cannot apply the behavior to all elements with the “small” class, as there might be other “small” elements outside the user list, so you would end up with some really obscure hacks to get it working correctly.
Now this is what you want to do:
<div class="users">
<div class="user">
<div class="name">Joe Schmidt</div>
<div class="age">23 years old</div>
</div>
<div class="user">
<div class="name">Johnny Bravo</div>
<div class="age">25 years old</div>
</div>
</div>
Arh, that’s better! Just look at it! Notice how style and markup are completely separated. If you want to change the look of how the user name is presented you can easily edit your ”.users .user .name” class in your stylesheet without having to worry about any markup. Also, now it would be extremely easy to add behavior when hovering the age elements without affecting other elements on the page:
// using jQuery:
$('.users .user .age').hover(function() {
alert("I am " + $(this).html() + " years old!");
});
So the lesson is this: Name your css classes based on what logical entity they are representing rather than how they should be styled.
I agree dude!
I agree! The majority of developers make this mistake – which as you said should definately be avoided!
I agree too, nice article again.
But I think this “rule” also has exceptions. It can still be necessary to have classes like .bold, .italic and so on. The very important thing is to use the different classes the right way – as always.