Class for Show, ID for (win)Dow
As I strive to be a diligent and disciplined developer, I am always looking for ways to improve my coding methods and development processes. I tend to take algorithmic approaches to methodology. I have thought a lot recently about proper use of Classes and IDs in writing my HTML, and there has never before been a black and white answer to when I should use which.
In general, most developers tend to stick with the classic definition of Class and ID. Classes are typically used when an element might appear more than once on a page so that the CSS only need be written once to affect all elements with the same class. IDs are typically used when an element is unique to a page and will only be used once on that page.
Classes for Style, IDs for JS and the Window
Besides their assigned definitions, what are the real differences between Classes and IDs in practice? Really, the only difference is the fact that an ID can be used as a “hash value” for a URL. This means that
www.myurl.com#my-section will load
www.myurl.com and will automatically scroll the window down to the element with the ID of
Styling an H1 tag? Use a Class. Use JS on one <nav> but not the other? Use an ID. Manipulate the JS Window Object to focus on an element? Again, use an ID. Maybe (hopefully) sometime in the future I will find a problem that makes me re-think my method. For now, this is my algorithm and I’m sticking to it!