Thursday, May 10, 2012

Semantic ClassNames

Yet another thing that pisses me off is the debate about using semantic ClassNames and finding faults with the usage of presentational classnames like ".h2",".col", ".span4" etc. There is nothing like a semantic ClassName in the w3c spec. If someone says you have to use semantic ClassNames, he/she is either WRONG or some SEO "expert" (which is even worse)!

ClassNames don't describe the content but identify the content.

Semantics live in the HTML tags and not inside a CSS class. Content-layer semantics are already served by HTML elements and other attributes. Class names impart little or no useful semantic information to machines or human visitors unless it is part of a small set of agreed upon (and machine readable) names (e.g. Microformats). The primary purpose of a class name is to be a hook for CSS and JavaScript. If you don’t need to add presentation and behavior to your web documents, then you probably don’t need classes in your HTML.

classnames are open to interpretations.

We presume every class name value will be in English, and every jerk looking at the source code will understand English. It’s all void if class name values are in German or Romanian. Even if, ideally, everyone would be comfortable in English, we’re presuming again. A classname like "code-red" might be for all elements that need to look red or might be a metaphor for some important content or technical description

Does that mean we can choose a classname like ".f8hyteolk"?

Yes and No.

classnames affect developers and developers should choose whatever works best for maintenance. If everyone in the team is comfortable with a classname like ".f8hyteolk" and understands what it does, then feel free to use it. Class names should communicate useful information to developers. It’s helpful to understand what a specific class name is going to do when you read a DOM snippet, especially in multi-developer teams where front-enders won’t be the only people working with HTML components.

How do we choose good classnames?

The priority when creating classes is writing ones that are maintainable, reusable and extendable. The most reusable components are those with class names that are independent of the content. I feel a class like ".block" is a better choice than ".news" or ".updates" as the former is more reusable and extendable.

A question to all those "semantic" classname preachers:

If a non-semantic class name is not in any way connected to the HTML element name, which describes the content just fine, and if there is not a single machine in the universe that will try to derive any meaning or “semantics”, from that class name, in any context, in any circumstance, and if that particular class name actually makes my code easier to read, easier to use, and easier to maintain, then why is it bad to have presentational class names in my HTML?