We use classes and IDs in our CSS to identify particular HTML elements. This is especially useful because it allows us to present the same kind of HTML element differently, depending on which styles we apply to the class or ID. For example, we could have several h1 tags on our page, but we can style each one differently by targeting each element by its unique class or ID. This is all well and good, but when do we use a class, and when do we use an ID?
The difference between an ID and a class is that an ID is only used to identify one single element in our HTML. IDs are only used when one element on the page should have a particular style applied to it. However, a class can be used to identify more than one HTML element. Also, when it comes to specificity in CSS, IDs are more specific than classes. This means that if an element has both a class and an ID applied to it, the ID styles will be the ones the browser displays.
In the case of my landing page, which I had divided into four sections, I gave each section an ID since I only needed to style each individual section once. I also used IDs to style any other elements that needed to have their own unique styles. I used classes to style everything else. I had a section that was displaying four different blog posts, but I wanted each blog post to have the same styling, so I gave each p tag the same class. By doing this I was able to style several elements at once, but only writing styles for one class.
Top comments (2)
I appreciate your article, but if I were a real noob reading this piece, it would seem to me like IDs exist for the purpose of applying CSS styling. But this is only a side effect of the ways that we can dynamically update CSS with JS.
An HTML ID allow for the unique isolation of a single DOM element - regardless of what we want to do with that DOM element once we've isolated.
With the advent of jQuery (and now, with
querySelectortools in standard JS), we can use a class as a "handle" that allows us to grab a whole slew of DOM elements But that's not what a class is for.
Classes are for grouping CSS attributes. IDs are for grabbing individual DOM elements.
Such a grear article, but some additional info: just to emphasise, within a page an id must be unique.
Most important: ids are automatically created as properties on the global window object.
Good to know, that the ids are linkable, so when you have an id=“here” and you visit your webpage as .com#here, the page will be scrolled to there (if neccessary).
An one personal opinion: using ids make the code hard to maintanable, coming from its behaviour. Because it can be applied to only one element, it can not be reused (nor within a page). Additionally, it has higher precedence than the class merhod, so you have to overwrite the applied rules with !important.
Always use classes, no matter what! :)