Best Practices for ID and Class Names
Published on August 12, 2008 (⻠February 5, 2024), filed under Development (RSS feed for all categories).
This and many other posts are also available as a pretty, well-behaved ebook: On Web Development. If the optimization of CSS is of particular import to you, Iâve collected several concepts in a brief book: CSS Optimization Basics.
Iâm working on another article for German Dr. Web mag, this time covering recommendations for IDs and classes, an issue likely as old as the Web itself. Taking a different approach than usual Iâm feeling free to publish a âguerrilla sneak previewâ in this place.
Talking about use of IDs and classes solely as style sheet selectors (as opposed to scripting hooks) and assuming knowledge about when to use what (I know that most of my readers are experienced), the best things to do are, in this order:
1. Keep Use of IDs and Classes to a Minimum
Unless IDs are needed for something other than styling (like serving as internal link targets), try to avoid them as well as classes as this is âcognitively easiestâ and the least of a maintenance burden. (Donât confuse structuralâwhich can always happen and against which you cannot protect yourselfâwith visual changes.)
2. Use Functional ID and Class Names
Deriving names from functionality (for example nav
, warning
) is usually the second-best option, as this is tied to the structure and helps conceptual understanding and collaboration. It is less of a maintenance problem as the page element in question might not change its meaningâand when it does, thereâs need for more substantial changes.
3. Use Generic ID and Class Names
If you cannot derive a good name from an elementâs function, or if you happen to introduce something solely for styling (e.g., for that still popular alternate styling of table rows), use generic, âneutralâ names (for example aux
or alt
, alternative). This isnât ideal for understanding and collaboration but it is less likely to impose maintenance problems.
Also: Use Names That Are as Short as Possible But as Long as Necessary
Generally speaking, try to get to the point (nav
), but donât sacrifice comprehension (about
).
⧠The truly worst thing to do, no matter what other people say, is to use presentational names (for example red
, left
, anything thatâs related to how an element looks or behaves). This has to be avoided at all cost as it cuts you out of the maintenance advantages CSS gives you.
Skipped here but likely to be included in that upcoming article are âchameleon semanticsâ and âpseudo-namespaces.â But maybe thatâs already telling đ
Update (August 19, 2021)
In his excellent A Philosophy of Software Design, John Ousterhout writes about the âvague nameâ red flag: âIf a variable or method name is broad enough to refer to many different things, then it doesnât convey much information to the developer and the underlying entity is more likely to be misused.â
You can apply this to generic ID and class names, too, which suggests to use generic names carefully. Theyâre more viable in small projects rather than large ones.
About Me
Iâm Jens (long: Jens Oliver Meiert), and Iâm a frontend engineering leader and tech author/publisher. Iâve worked as a technical lead for companies like Google and as an engineering manager for companies like Miro, Iâm a contributor to several web standards, and I write and review books for OâReilly and Frontend Dogma.
I love trying things, not only in web development (and engineering management), but also in other areas like philosophy. Here on meiert.com I share some of my experiences and views. (Please be critical, interpret charitably, and give feedback.)
Comments (Closed)
-
On August 12, 2008, 21:22 CEST, Seth said:
Outstanding. I agree 100%, that is how IDs and classes should be handled. Straight to the point đ
-
On August 12, 2008, 21:55 CEST, Robert said:
So, you are definitely voting against the verbiage of classes as introduced by microformats like hAtom, hCard and the likes?
-
On August 13, 2008, 12:53 CEST, Louis said:
Your first point is totally going in the same direction as Camen Design website. Interesting evolution of the markup I must say.
-
On August 13, 2008, 22:11 CEST, Jens Oliver Meiert said:
Seth, cheers đ
Robert, well, I already objected against microformats, but I wouldnât go as far as to raise doubts about every name they introduce. Many are okay, even though they lack a ânamespace.â
Louis, yes đ And actually, some of my sites, including this one, once took the same approach. Iâll write more about that âsoon,â too đ
-
On August 13, 2008, 23:08 CEST, Santhos Webdesign said:
Totally agree with this. Allthough I sometimes use names like left or red in classnames. Donât see why this is truly the worst thing to doâŠ
-
On August 19, 2008, 17:08 CEST, Niels Matthijs said:
Hmmm, when looking at ids and classes solemnly as style sheet selectors, I kinda have to disagree with you on the first point.
In your css file, do use ids and classes as much as possible, especially when the html element itself doesnât fully semantically describes the component you are styling.
Reason for this is that html might change, new tags might be introduced or new knowledge might be found (new discussions on semantics). The design has little to do with such decisions, so it shouldnât be linked to it.
Full article on this issue can be found here: leaving out css type selectors
-
On August 20, 2008, 11:15 CEST, Jens Oliver Meiert said:
Niels, who do you mean should âuse ids and classes as much as possibleâ?
Also, while I get the idea of what youâre trying to say, keep in mind that classes can be used more than once and on different elements, so there might be good reasons for, say,
th.alt
andimg.alt
(generic class name indicating âalternativeâ instances of the elements to be styled).[âŠ] -
On August 20, 2008, 11:45 CEST, Divya said:
This is a great idea. But I also think using ids should be kept to the minimum unless it is required.
-
On August 20, 2008, 17:13 CEST, Niels Matthijs said:
though I donât quite understand âwhen the html element itself doesnât fully semantically describes the component you are stylingâ)
What I mean by that is that classes are often a more flexible and solid solution for styling, Iâll try my best to explain with an example.
Take the case of marking up a telephone number. You probably have a div element with a class=âtelâ or something. Inside the div is the actual number. Now if you want to add a textual caption (like âTel:â) people often just include a span without any extra class as its not necessarily needed to style the caption.
The css will look something like .tel span {}
In this case though, a span doesnât describe what the element represents, itâs a structural html element that merely says âthis thingy is separated from the restâ. In this case, Iâd advise to add a class=âcaptionâ to the span so at least thereâs a significant semantic gain (you now know what the span represents) and style it accordingly.
The css now becomes .tel .caption {}
The reason I do this is because now I can more easily change the html if needed (it could just as well be a div, or who knows what they wille come up with later). As the span (=container) doesnât fully describe the component it represents (=caption) itâs better not to add your styles to it, as the html is not stable and could change.
This is a theoretical stance of course, if you worry about filesizes and minimal html/css this is probably not very useful, but my priorities lie elsewhere (writing flexible html/css)
Hope this explains a bit more what I tried to say đ
-
On August 21, 2008, 15:39 CEST, SITER said:
I often find myself using classes like ‘hiddenâ or ‘paddedâ. In some sense it feels bad, but in the other, it doesnât. In CSS, I define what padded means, and then assign it to elements like ‘article paddedâ. This is almost as bad as ‘redâ, but because CSS doesnât allow for proper inheritance, this will do for now. Please donât crucify me for this, i know the good and the bad of this. Itâs not the same as assigning style elements because for me ‘paddedâ might mean ‘padding:5pxâ or ‘padding: 5 10 5 20′ and i donât want to fix every element to the new set of values. I could also have ‘brandedâ or ‘attentionâ, so a div might end up with classes like ‘article padded branded attentionâ - kind of like tagging, but with CSS classes.
-
On August 22, 2008, 8:09 CEST, Jens Oliver Meiert said:
Niels, thanks for clarifying. This approach reminds me of microformats (along with the tendency to get a little excessive) but with the additional constraint that thereâs even less consensus on the meaning of the element in question (thereâs âenforced,â solid agreement on HTML element semantics, some agreement on microformats semantics, but less to none on âindividually assigned semanticsâ).
Apart from that, this seems to apply to cases in which HTML doesnât offer you specific semantics. While this can be somehow addressed by using certain class names, itâs fine to fall back to
div
andspan
for âneutralâ structuring. Thereâs nobody going for your âcaption,â in this case, anyway; âconsensus,â again. (I hope this made sense.)
Read More
Maybe of interest to you, too:
- Next: To Be Clear (on Conditional Comments and Resets)
- Previous: A Few Words on HTML/CSS Frameworks
- More under Development
- More from 2008
- Most popular posts
Looking for a way to comment? Comments have been disabled, unfortunately.
Get a good look at web development? Try WebGlossary.infoâand The Web Development Glossary 3K. With explanations and definitions for thousands of terms of web development, web design, and related fields, building on Wikipedia as well as MDN Web Docs. Available at Apple Books, Kobo, Google Play Books, and Leanpub.