Semantics in HTML is always a hot topic. Some people strive for it at all times. Some people critisize a dogmatic adherence to it. Some people don’t know what the heck it is.
I’d describe semantics as it relates to HTML as tags, classes, IDs, and attributes describing but not specifying the content they enclose. Let’s start with an example we can probably all agree on.
Bad Semantics
<div class="article">
<div class="article_title">Smurf Movie Kinda Sucks</div>
<div class="the_content">Not surprisingly, this weeks release of
<div class="darkbold">The Smurfs</div> kinda sucks.</div>
</div>
Good Semantics
<article>
<h1>Smurf Movie Kinda Sucks</h1>
<p>Not surprisingly, this weeks release of
<b>The Smurfs</b> kinda sucks.</p>
</article>
Whether or not you think HTML5 is ready to use or not, I think you would agree that when you need an HTML element for an article, that the <article>
tag is better than a generic <div>
with a class name. The title of the article becomes a header, the content becomes a paragraph, the bold-but-not-emphasized title becomes a bold tag.
But not everything maps that cleanly to HTML tags. Let’s look at a bunch of class names and I’ll offer my opinion on if I think it’s semantic or not.
<div class="column_1"></div>
Unsemantic. This is a classic example. Every single CSS grid framework in the world uses some kind of class names to declare the grids. Whether it’s “yui-b”, “grid-4”, or “spanHalf”, all of these are closer to specifying than describing their contents. So while I maintain these are unsemantic class names, I also think they are largely unavoidable in float-based grid-system layouts.
<div class="footer"></div>
Semantic. While a footer is an abstract concept, it has come to have meaning in web design. It’s the bottom of a website the typically contains things like repeated navigation, copyright, author info, etc. This class name declares a group for all that stuff without describing it.
If you’ve made the leap to HTML5, the <footer>
element would be better. And that goes for all the HTML5 elements. (Headers should be <header>
, sidebars should be <aside>
, etc.) If you aren’t yet using HTML5 (you better have a really compelling reason), the equivalent class names I feel are fine.
<div class="largeText"></div>
Unsemantic. This is specifying. Why should the text be larger? To stand out from other smaller text? “standOut” or “callout_text” might be better here, as in the Theoretical Redesign Future™, you may wish to choose a different style to make that text stand out that has nothing to do with the size of the text, and you won’t be stuck with an awkward class name.
<div class="priority-2"></div>
Semantic. I’ve talked with some folks from MailChimp (Jason Beaird and Aarron Walter) about this and this is how they declare the relative importance levels of buttons within the app (Although with class names more like “p1” .. “p5”). Higher priority buttons might have brighter colors or be larger, while lower priority buttons might blend in more with the content. By not being specific with what those styles are and abstracting to a priority level, you are staying semantic. It’s like taking the idea of <h1>
, <h2>
, <h3>
, etc. to buttons.
<div class="copyright"></div>
Semantic. If only every class name was this easy! This goes for any section which contains content that is easy to describe with a word like “tweets”, “pagination”, or “admin-bar”. Although with that last one, you’d be better off calling it “admin-nav” as in the Theoretical Redesign Future™ this area might not be a “bar” anymore.
<p class="introp"></p>
Unsemantic. I saw a presentation with Dave Rupert one time where he joked around that this was his favorite class name. I can totally relate to that as it’s such a common scenario to style the first paragraph of a page differently, like an attention-grabbing overview to get people into an article.
If you absolutely need super deep browser support, you might need some kind of class name, in which I’d say “intro” is better than “introp” (leave the element name out of it). But much better would just be to target the first paragraph like article p:first-of-type
or h1 + p
.
<div class="clearfix"></div>
Unsemantic. This is an extremely common class name, which applies a bit of trickery to get the element to contain all of its decendant floats rather than collapse. But it has nothing to do with the content it contains, thus unavoidably unsemantic. Dan Cederholm recommends a more feel-goody class name “group” for this purpose instead (in his book Handcrafted CSS), which, to me, just barely brings this into the realm of semantic, as certainly this wrapper contains multiple other elements and is thus a group (describing without specifying).
<div class="left"></div>
Unsemantic. Perhaps in the Theoretical Redesign Future™ you’ll want this stuff on the right instead. Too specific.
<div class="success"></div>
Semantic. I think this one works best in conjunction with other class names so that one of them describes the content and one describes the status of that content. Like “success message” which could hold a message like “Your file has been uploaded!”. If that message was “There was a problem uploading your file.” the class names could be “fail message” instead and have appropriate styling.
<div class="plain-jane"></div>
Unsemantic. This is trying to specify that the content inside should be styled a specific way. “plain-jane” is the same as something like “normal” or “regular”. Ideally CSS should be written so that you don’t need class names for “regular” styles, that just comes by default through the cascade, and anything that breaks that in unusual ways gets a class.
<div class="entry-unrelated"></div>
Unsemantic. Readability, the web app for reformatting and saving web pages for ease-of-reading later, has you use this class name to specify parts any elements of your site you don’t want to be accidentally included in the conversation/saving of your article. The reason I’m going unsemnatic here is because it’s describing what it’s not, not what it is. I wish there was something other than a class name that could be used for this purpose. Sort of like rel=nofollow
for links, but for content.
<div class="hyphenate"></div>
Unsemantic. Trying to specify the behavior of the content inside, instead of describe what it actually is.
<a class="link" href="#"></a>
Unsemantic. While link is descriptive without being specific, just the nature of an anchor link already makes it a link, thus not necessary. If the class name is trying to separate this link from other “normal” links, be more descriptive as to why, e.g. “book-link” or (debatable) “button”.
But…
Let’s say you have two types of articles on your site and you want to style them differently. Movie Reviews will have a blue background and Breaking News will have a red background and bigger text.
Here’s one way to do that:
<article class="movie-review">
...
</article>
<article class="breaking-news">
...
</article>
and another:
<article class="blueBg">
...
</article>
<article class="redBg bigText">
...
</article>
I bet if we had a poll and asked people which example they thought was more semantic, the first would win. It fits the bill put forth in this article: describing without specifying. Whereas the second example specifies (“blueBg” is a class name that applies a blue background). Let’s say the Theoretical Redesign Future™ stops being theoretical and is now in progress. The design for movie reviews now has a green background. The class name “blueBg” is rather awkward there. Whereas the class name “movie-review” is totally fine and you just change the properties/values to do the green background instead.
This isn’t to say the first example is hands-down always better. Let’s say that light blue color is used in a lot of places on the site. Perhaps it’s the background color of a particular part of the footer and a particular sidebar box as well. You might end up with selectors like:
.movie-review,
footer > div:nth-of-type(2),
aside > div:nth-of-type(4) {
background: #c2fbff;
}
That’s efficient because you are only declaring that color once. But it’s also a rather complex, hard-to-scan, unwieldily selector. Not to mention those different selectors may need unique styling, so they’ll have to be repeated later. Or you take another approach and just leave them separate:
.movie-review {
background: #c2fbff;
/* Plus other stuff */
}
footer > div:nth-of-type(2) {
background: #c2fbff;
/* Plus other stuff */
}
aside > div:nth-of-type(4) {
background: #c2fbff;
/* Plus other stuff */
}
That might actually keep your CSS file more organized (keeping different areas of the site in different sections) but at the cost of repetitive declarations. In a presentation by Nicole Sullivan I recently saw at the CSS Summit, she called out some big companies for declaring the exact same color in the CSS files literally thousands of times. I think we can all agree that’s crazytown. There may be a variety of solutions to that, but one of them might be using a class name like “blueBg” to declare it once in the CSS and then put the burden on the HTML for applying that class name when you want that design. Still, you’d be better off calling it “mainBrandColor” or “secondaryFont” as to avoid specifying. As I understand it, that’s OOCSS. Sacrificing a slight bit of semantics for the greater good (drastically smaller resources).
Would love to hear some of your opinions on all this. I’m sure plenty of you have other example, different opinions on what is or isn’t semantic, and whether or not that matters.
hahahaha! Love how you start off with the smurfs suck in the bad example, and carry on to the good example with how they still suck.
I never considered whether class “left” or “right” was semantic or not, but I suppose it is not. I feel like my world is falling down around me…
Not sure about the movie review/breaking news example. If “Breaking News” becomes “Latest News” for example, the original class name becomes confusing. Perhaps .movietype-1 and .movietype-2 would be better.
I think Breaking News & Latest News are similar enough that the semantics still holds. Having said that, if the content changes drastically enough (and not just styling) it’s likely you’d want to create a new class/style for it anyways.
Great article, I hark on (a little) about basic semantics sometimes, so I loved how everything was explained in your article. Awesome, thanks :)
I don’t use ‘left’ or ‘right’ as a class unless I’ve previously defined it in the CSS reset – for example, rather than adding…
…to my CSS element, I just call it in the reset – like so:
Then I can user later on when I’m defining element classes in HTML, I can use it to float that element to the left, or the right – like so:
Semantic, or unsemantic!? :P
I do that too, on occasion. I typically try to avoid it though, lol. It just depends on the project, and my mood I guess. Definitely interested what Chris has to say though!
Clearly unsemantic !
You’re defining the position within the html while it should be in the css…
… if you’re a semantic nazi !
If you’re not a semantic nazi, it’s “unsemantic”, but it may “do the job”. You should ask yourself “If I want to change the skin of my site, will it always be on the left ?” or things like that.
Writing semantic class name is a “best practice” because it allow you :
– To not ask youself questions about skins BEFORE you write your html trees
– To be better parsed by external tools (like search engines).
If you’re need doesn’t match the advantages of a “best practice”, you can do something else.
I think I just tend to do it because it’s easy to work with – and if anything needs re-positioning, then it’s simply a case of changing that word to either ‘left’ or ‘right’.
But I see your point. :)
Well, away from the main subject about being semantic or not. I think this would force you to work more and harder to flip your design direction from LTR to RTL or the opposite. Maybe you didn’t face this case, but as a UI developer who deals with Arabic speaking customers this would be a nightmare for me if I’m working on some large scaled project.
I’ll tend to use multiple class names like class=”meta right group”. I still don’t see anything wrong with using class names ‘left’ or ‘right’. Even though the left element might float right someday I’d just change the class name to ‘right’ and leave the css. Same goes for ‘grid’ class names. I much prefer tacking on class names that already have defined CSS as opposed to positioning and styling just about everything.
I still don’t really consider “left” and “right” unsemantic if they are being used to class something out that is not distinctive in any other way. Best to use your judgement – how is this best described to someone who isn’t you?
I’m with Denis. Why go through the hassle of writing float: left 50x? If you really are going to have to switch it to a float: right just switch the class to right.
This obsession with semantics has the potential downside of bloating up your css files. More css = less maintainability + harder to read. Additionally, creating “helper” classes allows developers to maintain consistent styles and allows anyone to understand what styling is being applied without having to dive into the css. If I have a left class and internally everyone learns what left is that means I don’t have to pull open “some-semantic-class- name” to find out it contains float: left or even create the class to apply it.
My rule of thumb is if it is going to have a lot more css than a simple “helper” class applies then I’ll be semantic through, since I’ll still need to crack open the css and see what else is applied to it.
Here are some examples of classes that can be applied to a ul where I work: padTop (converts from using margin-top to using padding-Top), sprited (for when each li contains a sprite), bulleted (for when we want to see the bullets).
All of this seems like a debate on “Is it right to go with semantics or not?”
I would do things my own way, and go with things that would make my work easy and not care about these hard and fast rules that we would define because of “semantics”
I think semantic on html should be limited to tag names.
id, classes and other properties can be what you want to achieve the visual design with css as you desire.
I wonder why we can’t put arbitrary tag names to enrich our semantic, there are only a bunch in html5.
Take a look at this for custom semantic tags http://sickdesigner.com/index.php/2010/html-css/truly-semantic-tags-and-html5/
Because arbitrary tag names have no meaning to anyone else but the one putting them in.
You can always use the XHTML of HTML5 to do that. Until those arbitrary tags are being documented at a larger scale, their semantic relies on their name, which are highly susceptible to interpretation.
And you can see that in current specs we use. The problem is not the small number of tags being used, it’s the right use of the existing one and that’s making a mess out of the web dev.
Oh, ouch! I know I have been guilty of some of these examples such as columns numbered and left/right. Like Dan, I never really thought about these class names not being semantic. Thanks for such a great article, I know this isn’t something I will forget in future designs.
I have a bunch of similar ‘helper’ classes I use as well that are used in additional to other (typically more semantic) classes. .tleft, .tright, .tcenter (for text alignments), .small (for small text), etc.
If the design needs to change, I remove/switch the helper classes from the html.
For the sites I do, so far the convenience of these helper classes has outweighed the cons of the minor changes to the html. It also helps prevent a lot of duplicate css declarations (using text-align:center on a hundred items that need it as opposed to doing it once and then using that class in a bunch of places).
“helper classes” is basically OOCSS as I understand it. Totally fine IF it actually saves you grief instead of causes it.
That’s means that that’s POSSIBLE for you to do. Generally, it is for me too. Most redesigns I do I have the power to change HTML just as much as CSS. But that’s not always possible. Think of this site, there are like 1,400 unique pages or something like that. Any HTML that isn’t a template but part of the content itself is pretty much set in stone, I won’t be revisiting that many documents to change HTML.
Ok, today in the morning I was thinking of creating a custom UI for my site, and came to my mind to create classes as:
And a few minutes later I see this post, after thinking better, I got the following idea, instead of specifying the color directly in the css, specify it in the name of the file containing the styles.
Something like:
/assets/css/ui/green/main.css
If the UI need to be red:
/assets/css/ui/red/main.css
What do you think?
Unless you’re allowing folks to change your UI color, or you’re building templates for sale, or plan on creating a bunch of UI colors that you switch between — what’s the point? If you’re not being color-specific in the CSS, why not just change the colors in the same CSS file when you change the UI again and forget about building a complicated directory structure, unless, again, you need the ability to switch between colors for some reason.
Yep, the user can change the UI color. So, this way is best.
Then you could just name them UI-color-1, UI-color-2 etc.
Yuh, I actually go as simple as: c1,c2,c3,etc.
Instead use names like: MainColor and SecondaryColor, or FirstColor and SecondColor (some will kill me for suggesting this ;-p) I always use something like CorporateColor and SupportColor.
While I immediately agree that names like “left”, “red”, “bigfont” etc. are bad. I would not immediately agree that classnames need to be semantic. For who or for what do they need to be semantic?
The user never sees them, the browser will happily render any name without caring what it is, and last time I looked I don’t think there is any software (spider) out in the wild collecting data from websites based on arbitrary semantic class names? Sure, a class-name like copyright might be used by some spider to collect information, but lets be honest here, it will most definitely never collect all it want because many copyright notices will not have a copyright class-name. Besides I may come up with a semantic class-name that is unique…what spider/software will ever know about it? AT (assistive technology) hardly uses classnames to convey information (I think I only ever heard of one instance regarding the “footer” and “header” classes and those are now full blown elements.)
So in the end, class-names -I think- are for the developer only. Thus the rule should be:
class-names and ids should make sense in style and/or content, even if either style or content is changed. Which no longer means they *have* to be semantic.
Unless someone can convince me that semantic class-names have a pure semantic reason I don’t know about?
I agree…class names are specifically for the developer. But what if you’re working on a project with multiple team members? You don’t want to create a class that is confusing or unclear to the point that your team members would have a hard time understanding them. And you also wouldn’t want them doing the same thing to you.
@Jordan: Like I said, use names that make sense even if style or content changes. I think that should be the rule. That means it could be semantic, but it doesn’t have to be. Besides, in teams it is always a good idea to use pre-agreed upon standards.
RIght, class names are only semantic for a human viewing the source code. They mean nothing to machines parsing a doc or building outlines.
I really like this article! Although it definitely made me feel bad about using `class=left`…clarity/accuracy in code is so often overlooked. I know I’m guilty of it at times. Great motivation to do better :)
I ran into an issue a couple months ago with @font-face. I caught myself using a class in the markup that had the font declared rather than declaring it multiple times throughout the stylesheet. In the end I realized it was just bananas to put that responsibility on the html and put it all back into the stylesheet. It did get me thinking of times when it might be more appropriate to use the html as a way to make things easier for others to understand when they are looking at your work.
But whatevs.
While most of this I agree with, I’m still not quite comfortable with switching to full CSS3 and HTML5 yet — at least, not in a normal web shop environment with clients who still can’t upgrade their browser. I know there’s JavaScript workarounds, but I believe the experience should be organic, not hacked. At some point in my career, I do hope to break the barrier and not have to worry about IE7/IE8.
At any rate, I’ve tried using the “.className:after {content: ”; display: block; clear: both;}”, but most of the time I end up using a <br style=”clear: both;” />, instead of a div with a clear class.
Everything else, I definitely agree on. I only use as many class names as I need, typically as few as possible. HTML has all the built in tags for formatting, there’s no sense in using Div’s for everything.
Well, the problem here is not that much about semantic or non semantic, but rather about “css has a lot of problem if you’re aiming at DRY” (DRY : Do not Repeat Yourself).
Imagine the following css :
classorelement1,
classorelement2,
classorelement3,
classorelement4,
classorelement5
{
cssproperty1:value1;
cssproperty2:value2;
cssproperty3:value3;
cssproperty4:value4;
cssproperty5:value5;
}
classorelement6,
classorelement2,
classorelement3,
classorelement4,
classorelement5
{
cssproperty6:value6;
cssproperty7:value7;
cssproperty8:value8;
cssproperty9:value9;
cssproperty10:value10;
}
classorelement2 to classorelement5 are complex selectors, they always come together. You don’t to repeat that section because it’s always the same. You can them write :
classorelement2,
classorelement3,
classorelement4,
classorelement5
{
cssproperty1:value1;
cssproperty2:value2;
cssproperty3:value3;
cssproperty4:value4;
cssproperty5:value5;
cssproperty6:value6;
cssproperty7:value7;
cssproperty8:value8;
cssproperty9:value9;
cssproperty10:value10;
}
classorelement1
{
cssproperty1:value1;
cssproperty2:value2;
cssproperty3:value3;
cssproperty4:value4;
cssproperty5:value5;
}
classorelement6
{
cssproperty6:value6;
cssproperty7:value7;
cssproperty8:value8;
cssproperty9:value9;
cssproperty10:value10;
}
But you don’t want to repeat cssproperty1 to cssproperty5 nor cssproperty6 to cssproperty10 beacause you don’t to maintain but “exact same sections”.
css don’t help you here… You can use classes like in this article perhaps you have severals skins and the “bgBlue” doesn’t make sense in other skins…
The best solution I found : LESS or SASS.
Using those meta-css tools, you can factorize your css without having to require to use a class. You can write you “background color” once.
SASS (or more current and appropriate SCSS) is most definitely the solution in for all CSS needs. It gets closer to doing what C++ did to C (objectifying the language). You can make functions (or mixins as theyr’e so-called), as well as entire objects with specified styles. I can almost guarantee that those companies that had _thousands_ of the same color defined probably SASS. It’s just not sustainable to maintain CSS to such extremas without variables.
To be a pedant about semantics, you should be wrapping “The Smurfs” in <i&rt;The Smurfs</i&rt; since it’s a major work and should thus be italicized. I can see the argument for this being unsemantic, but it’s really not since anyone that has written a paper in school (at least in the US) will know this rule. Even if you do want to argue that it’s so unsemantic as to exclude it, your <b&rt; tag is no better.
I could see <cite&rt; having a bit of argument for it, but that’s fairly vague too.
No, no, no – you’re missing the point. Add a class to the header saying that it’s a movie (.movie, or .movie-title perhaps?), and let CSS do that for you. If it’s used outside of the heading, I’d agree that a cite tag would be vaguely acceptable, though a span tag would probably be a less-disputed choice, since there really is no HTML tag specifically for it.
My favorite class that I’ve seen used was on Facebook:
Profile Headlines – .ginormousProfileName
One could certainly argue whether or not that’s semantic, especially considering Facebook’s proclivity for redesigning.
A problem I’ve run into is WordPress themes that use the body class, but give the class of “page” to the div that wraps the main article – and then when you try to declare a width (or whatever), it’s applied to the whole site. I prefer “content” for the div in this situation.
Awesome article, though I feel like this could be followed up by an article on “Underused, but semantic HTML” – stuff like <address>, <acronym>, <abbr>, <dfn>, <q>, etc.
The priority when creating classes that is writing ones that are maintainable. No browsers or spiders care about the value of your class attribute (with the explicit whitelisted case of microformats).
So whether its semantic or not doesn’t matter in any practical sense. If you think “group” is gonna be more maintainable for you than “clearfix”, fucking go for it. Personally I use a mix of whatever makes more sense. Sometimes more maintainable classes means ones that indicate some of their presentational aspects when I look at them in my stylesheet, so I remember what they are.
When I saw the title of this post, I thought “Paul will have something to say about this….” :)
I think there is a difference between (for lack of better descriptions) “big sites” and “small sites”. The bigger the site, the more content, the more it will benefit (long term) from trying to be as semantic as possible with class names.
Can anybody argue this guy is in a good position?
I have to agree with Paul Irish on this one.
The class name values are not standard, like tag names, for one.
Secondly, a class name value doesn’t describe, it identifies, you’ve said that yourself Chris.
You can’t be semantic about an id value. It’s like trying to say 1 always equals to 1 apple.
While Chris may mean something, its origins and stuff, it’s certainly not semantic, it’s just an id name value to randomly id a person ;) And so is Coyier, the class name.
So arguing that “p1” is more semantic than “bigBlue”, because “p1” has a hidden “priority-1” meaning, it’s childish.
And even more childish is to invent an English language html-discovery course where you start defining that “priority-2” and “plain-jane” are different in semantic mechanism.
They’re really not. Neither describes position or color. And both imply a more or less of something, without being too specific about that something. So they both qualify the same.
Trying to add semantic to values that really should be surrounded by quotes that designate an arbitrary string, its a fool’s game. And every milliner in town is going to want to write an artistic review as to the real hidden meaning of it. Something like in poetry, only worse.
I’ll argue that “p1” is more semantic than “bigBlue” until I’m bigBlue in the face. The day comes that you don’t want that element to be big or blue anymore is a sad, sad day.
It might not “matter”, in that you might not care, search engines don’t care, people viewing source are jerks anyway, etc. It matters in a more subtle sense. It’s like a light switch that you have to put in the off position to turn on. It’s annoying every single time you have to deal with it. Or what if you had to log in and out of your email client for every email you read. There is nothing wrong with that, it works perfectly fine.
Two good ones: bigBlue and jerks looking at the source code. LOL!
Well, in case of p1 actually meaning the color purple, shade #1, I guess you’ll have to argue for as long as it takes for you to get purple #1 in the face ;)
Joke aside, you presume. You 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, you’re presuming again.
You presume that big Blue can be interpreted in just one way. bigBlue can actually be a metaphor. Like “priority-1”. A military code, a technical description, anything.
Two things, just to clear the air.
Don’t get me wrong, I’m more than “Yay” for using meaningful values for class names. And I don’t mean “green”, “left” etcetera, but values like “movie-review” and so on.
That said, I’m not going to get out of my way and start a religion over it. I’m practical about it, above all.
A simple search and replace solves the problems of class name changing, that not-so-dreadful day come, and my content and its markup have already plenty to say, making my carefully chosen semantic class name somewhat redundant.
Great article, Chris. I manage a team that maintains somewhere around 13 fairly large sites. We try to keep things semantic, but we definitely slip up. Luckily, find+replace tends to work well in those instances since we use pretty unique class names.
However, when does it go too far? For instance, in your example: “class=priority-2”
What if those blocks need to change to a different priority during the next redesign? “priority” makes it a bit too specific whereas “p2” may work better, although even that (along with h1,h2,etc.) could be argued to be unsemantic, no?
Paul is correct. How refreshing to hear some common sense on this topic!
“Semantic” class or ID names give zero benefits to users. They only affect developers, and developers should choose whatever works best for maintenance.
This is totally different from semantic HTML tags. Semantic tags help users (and search engines).
You can really bend yourself out of shape trying to force your classes to be “semantically pure”. It’s a manifestation of OCD; code should never become religion!
What makes this especially absurd is that most HTML classes are used purely to help us apply presentation with CSS. These classes are not really structural semantics (describing the semantic structure of the document). Instead, they are what Nicole Sullivan would call “visual semantics”: they describe the structure of the presentation layer.
Nicole’s OOCSS approach isn’t just about performance; it’s also about improving maintenance. You can also use SASS to get similar maintenance benefits, but then you lose the performance gains from OOCSS.
Pragmatism is the best approach. Generally speaking, there’s no need for hostage-to-fortune class names such as “big-blue-italic-text-against-a-mauve-background”. Equally, there’s no need to rewrite a grid system’s classes such as “col1”, or even “leftCol”.
I found an article that offers a delightful reductio-ad-absurdum against seeking 100% “semantic purity”. This guy was trying to make OOCSS grid classes (“size1of3”, etc.) more “semantic”, by assigning columns names such as “rhythm”, “wedge”, and “beat”.
http://revoltpuppy.com/txp/articles/5/making-oocss-more-semantic
The twisted logic he used to justify these “semantic” names just shows how creative people can be when trying to force a round peg into a square hole. Bless his cotton socks. ;)
Our p1-p5 button classes have come up a few times in this comment thread so I thought I’d clarify. Those classes are really just color modifiers for our base “button” class. We could have just used “bigBlue” as IT Mitică suggested but that would have been a nightmare when we redesigned the app last year and all of our button colors changed. We also recently added a co-branding feature that allows people to customize the interface, all the way down to the colors of those p1-p5 buttons. These modifiers are used on every button in the app and the most common priority (p1) is referenced more than 200 times in our source code. Because those classes are not tied to a specific adjective, we can modify them with 1 line of CSS without having to dive head-first into the markup haystack.
As Paul said above, “the priority when creating classes is writing ones that are maintainable”. I’d add reusable and extendable to that list. Don’t try to invent a new language for some element you’re only going use once or twice. If it’s a markup pattern you’re likely to reuse though, a semantic naming system that isn’t tied to a visual description takes very little effort now and will spare you a lot of hair pulling later.
I was writing my last comment as the previous one came in. Just wanted to say that we also use Nicole Sullivan’s OOCSS in MailChimp and it works great for us. One could definitely argue that class names like “size3of4” are tied to a visual description, but as the previous commenter said, trying to “semanticize” a grid system is just trying to hard to force a peg through a hole. Unless your redesign it a total tear-down job, the grid system you use probably isn’t going to change.
Jason, however improbable, that day may come, sooner rather than later, when you’ll need to drop the grid system.
That means that while I agree that “p1” is more maintainable that “bigBlue”, “size3of4” is still prone to give you headaches in a not so distant future. Says me :)
And to be perfectly clear, “bigBlue” it’s simply a 5th grader’s choice.
When illustrating strictly, ad verbum, a-likely-to-suffer-style-changes big blue thing, it should be avoided at all costs as a class name value, no matter the language: “grosBleue”, “großBlau” or “mareAlbastru”.
Why? Cause we’re smarter, right? ;)
“Jason, however improbable, that day may come, sooner rather than later, when you’ll need to drop the grid system.”
…in which case, you change your HTML. But your website has thousands of pages? Find-and-replace.
Any major redesign is going to require some markup changes anyway. You will never get 100% perfect separation between presentation and structure, or even between presentation and content.
One example always gets quoted to support the myth of CSS-only redesigns: CSS Zengarden. But take a look at their markup. Can you tell me it’s “semantic” and keep a straight face?
Does it really matter what names you give to your classes and ids?
Do you imagine visitors landing on your site immediately hit the View Source button to carry out a comprehensive survey of how “semantic” the names you have assigned in your code are? Of course not, they couldn’t give a rat’s backside. As long as the pages work and look nice they couldn’t care less if you have used the names of the twelve apostles, the Man Utd first team or the defendants at the Nuremberg Trials.
Semantics, shmemantics. It’s this sort of mumbo-jumbo that gives web design a bad name and sends prospective punters running for the hills screaming.
If the names you use are meaningful to you, then who cares?
Unless of course you think the only people using your site are other web designers looking to pick the bones out of how semantic your id and class names are.
From your website: http://cl.ly/916J
I’m the one giving web design a bad name?
It’s not about viewing source, it’s about doing a good job with the code you write so it’s easier for you (and those after you) to work on that website.
Well I think that proves my point.
Are you seriously trying to say that a piece of code will work better if you assign it, class=”summat-profound” than if you give a bit of, class=”qwerty” ?
Of course it won’t, they will both work exactly the same. The code doesn’t care, the browser doesn’t care and more importantly neither do the visitors or the search engines.
I’ve used #asd and .zxc before now, works a treat.
Sorry but my view is that functionality makes it easier to build and maintain a site. Perhaps it is my background in mechanical engineering but if class=”left” or class=”right” is descriptive and functional then that is all that matters.
“I’ll argue that “p1″ is more semantic than “bigBlue” until I’m bigBlue in the face. The day comes that you don’t want that element to be big or blue anymore is a sad, sad day.”
When the day comes call it “smallGreen” or “mediumsizedRed”. Call it “arnold” if you like. :)
No the code won’t work any better, but working ON that code will be better.
If you are completely 100% OK with writing class names like “mediumsizedRed” but really in the CSS it applies styles that make the font tiny and the color a light gray, that’s great. Of course, it will work. But: 1) I will never hire you 2) I will never work on an open source project with you 3) I will secretly laugh at you while pulling wheelies on my fixed gear bike.
@Chris, I’m pretty sure you just pwnd him with that screenshot. I hope a CMS is generating all those inline styles because that’s going to be hell to cleanup down the road.
@NigelC It would be a great benefit to you as a designer to open your mind to this article and others like it. If you did, I bet you’d be surprised how quickly your opinion would change. :)
Oh Nigel, Nigel, Nigel… wow.
That was the best screenshot ever.
I guess many CSS styles on sites evolve over time and constant development – like mine, and through the learning curve of the developer as he/she learns how to do it properly – like me. No doubt many of us would do it differently if we started from scratch.
Or maybe not.
I too suffer from having greenbody or smallheadinggrey
I just love this type of content!
Perhaps an easier way to explain semantic CSS is simply, don’t name your classes or ids anything related to a CSS property. A property could be color, font-family, float, border, background etc. Jens Meiert maintains an excellent list of CSS properties on his site – http://meiert.com/en/indices/css-properties/
Another way to look at it is, don’t name your classes or ids something that visually represents the element on your web page. As people have have mentioned before, this could be words like left, right, large, small, blue, green.
Great article Chris, I love this kinda stuff :)
Coupla HTML5 points: you can use
<small>
for inline copyright text, which probably wouldn’t need.copyright
. Also<aside>
has the right semantics to replace.entry-unrelated
for Readability.I’m all for OOCSS and I like short, non-specifying class names. For example, in space.css from OOCSS, you have these class names like “pan” (stands for padding all none), or “mlm” (margin-left medium), etc. I love these classes for adjusting the space between my elements/objects. Also, If you look at your gmail’s html, you’ll notice a lot of short, code-like class names with no apparent meaning.
Yep.
I just discover this post. and the funny thing is that morning I built a mockup and I made this reflexion :
My goal was to differentiate two kinds of profile : , same font and look except the colors : standard in green) and personalized in red).
Is it more semantic creating two classes, standard and perso with their respective colors than creating green and red classes… ?
choice 1 :
.profile { // all the common stuff}
.standard {color:green}
bla bla
Choice 2:
.profile { // all the common stuff}
.green {color:green}
bla bla
Of course standard and perso seem to be the right answer …
because the important thing isn’t the look, but the profile category.
Adding some colors class definition is exactly the same as the use of “FONT COLOR” tags.
Isn’t id is more “semantic” than using a class here?
<div id=”footer”></div>
You don’t need 100% semantic code to run a site, sometimes even unsemantic is easier to understand. Grid system is one example. Better have non-semantic class names in html than overbloated and confusing css file.
Analyze pros and cons at each project, and identify if being semantic will cause more problems than it will solve (some projects have short life-span or won’t be changed without updating the markup)…. Semantics is overrated, be pragmatic.
Interesting to read some of your views on semantics. I argue that there are still valid reasons for using the (where no other element is appropriate), mostly because of the immaturity of HTML5 support and the difficulty in styling the semantic elements cross-browsers.
The .hyphenate class (which I tweeted to you the other evening) is actually a jQuery selector for hyphenate.js plugin, and as such, is functionally semantic in the sense that it used to target each and every element on the page to receive the hyphenation treatment.
I think it’s a case of being ‘sensible’ with your naming conventions, being clear to distinguish between what is styling, what is a target for a jQuery function, and what is a helper class.
Great article. Just wish posers like this didn’t rip your content.
leonardowesleidiniz.wordpress.com/2011/08/04/what-makes-for-a-semantic-class-name/
…I can’t believe so many people in the comments have used ‘left’ classes. wow.
Well then, what would you suggest as an alternative? I constantly hear people bashing the “left” and “right” classes but no one seems to have a solution.
For instance, how else is WordPress supposed to float:left an image within the copy without adding the “alignleft” class?
Most interesting is That many css developers use the totally misplaced class of “clearfix” That can Be replaced and insted use overflow=”hidden” in the main content div to control the clearing of the alignment. It’s a easy trick and eliminates the ugly unsemantic clearfix class.
For preparation of html5, it’s recommended to class the divs as the article, aside, or footer and all the others … to easy be able to change the validation when the html5 is ready fully to use…
I’ve posted my thoughts here already, but since then I’ve been doing a bit of code-reviewing and came across this absolutely classic.
.centered450left
I didn’t know whether to laugh or cry!!!
I’ve rejected the changeset and suggested the offending developer renames the selector to .wtf
great article. thanks Chris.
as a beginner I have to admit I haven’t thought much about it.
I use these
and apply these whenever those needed like this
are these semantic or unsemantic?
Oops. *
A few years back I was working on migrating Hewlett Packard’s world-wide partner portal (today “HP Smart Portal”) from the legacy BroadVision Javascript to a rewritten Java solution. At the same time we were provided a so-called “HP Web Standards” style guide that was mandatory for any HP site all over the world. I could dig up a direct link to one of the – still actively used – style sheets:
http://welcome.hp-ww.com/country/us/en/styles/hpweb_styles_strd.css
While they did define a lot of semantic class names, they also brought things like these:
a.colorFFFFFFbld {font-weight: bold; color: #FFFFFF;}
.large {font-size: medium;}
.color333333bg {background-color:#333333;}
.colorDCDCDCbg {background-color:#DCDCDC;}
.color666666bg {background-color:#666666;}
I guess we’re lucky to be allowed to see the CSS definitions, because we’d be having a really hard time guessing what effect these classes would have if assigned to an element in our markup :)
Cheers,
Uwe
After reading some more comments I am still not convinced. Like I said above, and many others as well. Why Semantic? I agree p1 is also rubbish and as is any name which makes no sense. But why keep at it with ‘semantic’?
Why does it matter it is semantic so much? Again (I keep repeating myself) if a name is understandable and makes sense, even after you change either the style or the content it refers to; then why does it matter if it is semantic or not? I am suspecting that this is a remnant from the table vs css time and someone just super-positioned the argument for semantics on css as well because of maintainability. But semantics and maintainability have nothing in common, are not related and don’t need each other to exist.
I really would like to know why you think semantics is so important when “makes sense” makes so much more sense. (I’ll agree that semantic names generally make more sense but they also limit you without reason, and there is a sea of names out there that are perfectly usable & maintainable without being semantic).
mmm. nothing in here is semantic for me: I speak Spanish and <h1&rt; should be <c1&rt; (c=cabezal=heading in plain english)
Since the view-source html is already a messy place, especially when minified. I think its best to keep your template.php and css understandable. Whether thats through semantics or OO … just means to an end.
I guess another question is how well semantic search techniques will improve – it’s progressing and seems likely to me that as people are lazy that will become more important than the markup anyway???
Sematic lives in the HTML’s Tag names.
Sematic does not live in CSS’s class or even id.
Sure it does. I’d say that it’s equally as relevant to the term “semantics”.
A practical, real-life example of a user agent drawing semantic data out of class names is Google’s crawler, when it searches for microformats like hCard and whatnot. So sometimes the semantic value of a class name is useful to more than just the developer.
Ok now ,
If u r really that sematically sematics, then i think we should propose the new HTML’s attribute names “sematics” along with “class” and “id”
Don’t kill the sematics aspect of stylesheet ( CSS ) as it is for – to style the element with “class” and “id.”
Instead, use this new attribute for sematicas purpose only.
That means we will have one more sheet called cascading sematics sheet ( CSeS ) for its very own purpose.
Hi,
I think you are making good point… but you haven’t thought it all the way through… not every view/display has semantic…
Of course article teaser should be classed as teaser not textInItalics and you serve the reason: redesigning such content to bold would be pain… but consider this:
you have an article with a lot of tangential content… you use aside element and style it… all aside element within article are the same with one exception: float; the first floated to left, the second to the right, the third to the left… what semantic is there? It would actually be counterproductive to try to assign some semantic there… classes like floatLeft, floatRight are much better, because (if you use semantic classes when appropriate) it shows, that there is notning special, semantic at all… those classes are just for box alignment…
So yes…. semantic classes are the best choice for semantic content… but there is no reason to force semantic when there is not any.
I use semantic classes heavily, but there are often classes like .clear, .alignLeft(right, center), .floatLeft(right) etc. in my CSS just for view/display purposes.
Hear hear! I think that, in some cases, pragmatics really do win. My understanding of classes is that, if there’s no selector for them, they just get ignored and nobody gets hurt. So leave out the .floatLeft declaration for the mobile stylesheet (or overload it, depending on the way you write your CSS), and the ‘meaning’ of the document isn’t changed anyway.
After all — and this might be a bad thing to say among this crowd — user agents don’t care about our good quality class names (microformat parsers notwithstanding), and it certainly doesn’t help accessibility in the same way semantic elements and ARIA roles do. So what are they for? Us developers!
At the end of the day, I intend to adopt semantic CSS to make maintenance easier, and I intend to adopt unsemantic CSS for the very same reason.
Thanks for this useful article. Best regards.
This is an interesting article although somewhat bogged down in technicalities in the comments. Isn’t the whole point of thinking about semantics when it comes to coding a webpage about separating style from meaning?
The idea that we code a webpage and it is displayed on different platforms in different formats means that it’s code should deliver as much of the meaning as possible while the display/device defines the style.
From my point of view, giving a heading tag the class of. article-title is much more meaningful that .big-blue. As Chris says it’s easier to understand and maintain – and in an abstract sense contributes to the overall meaning of the document.
.big-blue is, I think, the first step on a slippery slope down to and then there’s nothing for it but to start using tables again…
Oh dear, I think I’ve been doing it wrong for so long now… I always have a list of classes with common proprieties like
.fleft { float: left; }
.red{ color: red; }
.blue{ color: blue; }
.big{ font-size:120%; }
.clear{ clear:both; }
…….
It’s very easy to change colors/layout this way. But I guess I should rethink my methods now….
I’m a semantic nut, I love this article. lol
I typically try to name all my elements by their structure, not behavior or “style.”
Like in OOP, you could have a could do something like:
Object = animal
class = reptile
class = mammal
class = amphibian
In terms of CSS, I would definitely consider
I’d also consider semantic. Thinking in terms of structure and priority is key in my opinion. I just apply this principle to all of my CSS. Styles change all the time, so I avoid getting too specific.
What I’ve learned is that in coding/programming, the real power is in generics. This allows you to apply your work easily to multiple projects and be more product. :)
Wow, for some reason my comment got all jacked up. lol oh well
<i><small>Tried to post earlier but didn’t see it, so sorry if this is a duplicate.</small></i>
Great post Chris!
I must admit, I have been guilty of a few of these non-semantic class names. Ones like “left” and “right”. I mostly used these in column layouts but have later moved to pseudo classes like :first-child, last-child, and :nth-child.
Since I read the article http://24ways.org/2008/making-modular-layout-systems I have been using it relentlessly. I always had an inner discussion how and when to use those. I want to maintain a flexible css, and something that one day, my successor will easily understand.
For items that have nothing other then color, font size, or font-weight styling to them, for some reason (not headers, or specific item), I am using the .fontsize_1.2{}, or color_#333{} classes. But you raised some good points and I must admit, I should change partiality how I work. I should do better job with that, I guess :)
SCSS and Compass helps keeping semantics in the house thanks to the @extend feature. It allows me to have reusable CSS properties in a selector, like:
And then, whenever I need it, I can call it semantically:
What SCSS actually does is add the extending selector to the extended selector. The CSS will come out with both selectors:
Of course, there isn’t any markup using ‘the-clearfix-we-see-all-the-time’ as a class. That’s why I picked a name I’m sure will not show up accidentally (I usually start these bogus selectors with ‘.-class-name’, since it is valid but not used).
This approachs works pretty well for Blueprint and other grids (see Compass Blueprint support), clearfixes (Compass provides clearfix mixins as well) and OO CSS. Semantics and DRY for the win.
As someone who has developed wordpress templates for those with zero coding knowledge, it actually is beneficial to have classes like left, right, and clear for the sole purpose of having these classes in the classes selection tool so the post author can select an image or some other element and float it without having to have any knowledge of the code.
I would even argue it’s impossible to have a semantic class here. What would it be called? It’s sole purpose is to float the element, and the same type of element in the same article might be floated left or right depending on the layout of the article. I can’t select by :first or anything like that because it’s arbitrary to the article layout created by the article’s designer. Sure if it was me, I would go to the html view and add the float to a style attribute, but it’s different to ask a non-coder to do the same thing.
Author,
Great “Grouping of words” + “Examples” + “user comments”. nicely done.
-user.
sorry – didn’t want to be too specific =)
Very good article, I especially like the p1 – p6 trick I can’t believe i had never thought of that. Also I commend you for bring up a valid counter argument in your post.
PS. As always well done on the redesign it’s a beaut.
Ah, got a real-life example here today.
I have a form with about 30 labels in it. 26 of those are 350px wide. But the remaining 4 are full width.
There is no way to distinguish those 4 from the rest in terms of simple css selectors, all labels are siblings. So the only way to be able to hook them is by giving these 4 a class. Now what to name this?
‘fullwidth’ comes to mind first, but obviously that is too style specific.
3 of those labels are checkboxes (while all others are not) so I could name those ‘checkbox-width’ but that still leaves the fourth one and besides what is to say I cannot have a checkbox in the future which is 350px wide?
The actual content varies from choosing a gender to accepting T&C.
I think I will go for ‘form-alternate-width’. I am wondering if I should include a number to that just in case I may have to add another width in future?
But even though the name is style related, non semantic and limits me in certain ways. it is easy to understand (both from the HTML file and the CSS file) and therefor to maintain.
I could also have chosen label-alternate-width, but decided against it since this limits me to labels only and that width is actually used on a [select] as well, so I can reuse it there.
@Evert: In regards to your real-life form issue, I can definitely understand what you’re saying. I’ve encountered the same problems, and they don’t easily go away, because in order to design a usable form, you need to have enough hooks so you can make the thing look pretty. And you want reusable CSS that you can utilise in five different unrelated forms on the website.
I can’t think of anything purely semantic, other than having a class name for each different type of field (e.g., .label-firstname, .label-province, etc). You could then group each size of label into its own declaration, but that could create quite large and horrific selectors. Using :nth-child(), +, >, and other bits makes for a management headache as well, because what if the number of form fields changes (which, in my forms, they do dynamically based on the customer’s settings).
My recommendation? Just create an easily-maintainable, unsemantic class for the alternate size of label, and be pleasantly surprised at the end of your life when you actually don’t go to hell for your transgression. That’s what I did :-)
Anyone else wanna weigh in on this?
What makes good semantics? wouldn’t <strong> be a better choice?
Well, no matter WHAT happens (except switching to HTML5) I’ll stick with my class nomenclature that corresponds to it’s function. I know that someone would have a hard time going through the code I’ve written, but if I’d work in a team, I would undoubtedly use the class names we’ve all agreed for to prevent confusions that would surely happen.
Oh, semantics. Another one of those things for anal ubergeeks to look down their noses at us muggles.
Fortunately, Mr Coyier is not one of “them”. Another helpful article, thanks.
I write code for a living and always look to improve its readability, and appreciate this article for helping bring some clarity to another of the dark arts of development.
Wish there were more like Chris who use their knowledge for educating rather than abusing.
Wouldn’t it be wise to adopt more semantic code practices and habits, come html 6 and up, these will be more widespread throughout the markup.
Good article. I know it’s a bit nit picky but referring to your first “good example” wouldn’t it be better to use <strong> rather than <b> since <b> is considered a presentational tag whilst <strong> is a semantic tag.
I did that on purpose to spark that discussion. The
isn’t deprecated, you just use it when you are making a word bold because the style demands bold, not just “to stand out.” or “extra emphasis.” In that sentence I wasn’t trying to emphasize the title of the movie, it’s just mandated by style to be that way. (although probably supposed to be italic.)
I’m curious no one mentions the fact that using a class or ID in your CSS is faster to render than using a tag as your selector.
E.g.,
.header {}
is a more efficient selector thanheader {}
.This doesn’t matter much when you’re building a small-scale site, but it’s certainly a good habit to cultivate, for the day may come when you need to optimize your CSS that much.