Welcome to the Treehouse Community
Looking to learn something new?
Saundra Howard4,688 Points
Can someone help provide clarity on when to use an ID vs. a Class Attribute in your mark-up?
I have a general understanding of the difference between the two but I still get confused when I sit down to write code. Do either of them have benefits over the other?
Erik McClintock45,783 Points
IDs and Classes achieve a similar goal, but in different ways. When you use them is defined by their individual intent, and then to some extent, personal preference. There are a lot of articles these days on the battle of using classes vs IDs, but ultimately, they both have their uses.
IDs are UNIQUE, and can only be on a given page once. By that, I mean individual IDs. You can have multiple elements with IDs on a single page, but the IDs must be different from one another, and any given element can only have one ID attached to it. For example, you can have two different paragraphs, and both paragraphs can have IDs, but they can't both have the ID of "paragraph". One would need to be something like "paragraph1", while the other was "paragraph2" (you, of course, would want to create more descriptive ID name than those, but this is just for simplicity's sake in this example).
Classes, on the other hand, ARE REUSABLE, and are meant to be applied to things that are more or less part of a group, or that will share styles across the page/site. In the example given above with the two paragraphs, if you were intending to style them the same way, you would give them both the same class (of, say, "paragraph") and then write styles for that class once, which would end up getting applied to everything that had that class attached to it.
In general practice you dont have to overthink it too hard. Most people use classes for most styling because its easier to keep track of only one than remembering if the element you made is going to be targeted by an id or a class every time you swap over to your CSS from your HTML.
Once you start implementing js/jquery, you'll need to pay a little more attention as you can add/remove classes etc. But until then I wouldnt stress it too much, or even spend an unduly amount of time trying to decide if each element is better off as a class or an id.