The important difference is that ids are unique, while classes aren’t unique. we will use the same class on multiple elements, while id’s must be unique to one element on the page. Id’s may appear to figure even when duplicated on the same page, but duplicate id’s will cause inconsistent behavior and difficult-to-find bugs. so now we will learn when to use class vs id in HTML.
when to use class vs id in HTML.
ID’s are unique
- Each element can have just one ID
- Each page can have only one element with that ID
When I was first learning this stuff, I heard over and over that you simply should only use ID’s once, but you’ll use classes over and over. It basically went in one ear and out the opposite because it sounded more like a good “rule of thumb” to me rather than something extremely important. If you’re purely an HTML/CSS person, this attitude can persist because to you, they really don’t seem to try to to anything different.
Here is one: your code won’t pass validation if you use the same ID on more than one element. Validation should be important to all or any of us, in order that alone is a big one. We’ll re-evaluate more reasons for uniqueness as we go on.
- You can use the same class on multiple elements.
- you’ll use multiple classes on the same element.
Any styling information that must be applied to multiple objects on a page should be done with a class. deem example a page with multiple “widgets”.
You can now use the class name “widget” as your hook to apply the same set of styling to each one of these. But what if you would like one of them to be bigger than the other, but still share all the opposite attributes? Classes has you covered there, as you’ll apply more than one class.
No have to make a brand new class name here, just apply a replacement class right in the class attribute. These classes are space-delimited and most browsers support any number of them (actually, it’s more like thousands, but far more than you’ll ever need).
There are no browser defaults for any ID or Class
Adding a category name or ID to an element does nothing to that element by default.
This is something that snagged me as a beginner. you’re working on one site and figure out that applying a particular class name fixes a problem you are having. Then you skip to another site with the same problem and try to fix it with that same class name thinking the class name itself has some magical property to it only to find out it didn’t work.
Classes and ID’s don’t have any styling information to all of them by themselves. They require CSS to focus on them and apply styling.