Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

MOD YOU UPP

macrumors newbie
Original poster
Jul 21, 2010
13
0
I was just wondering what the advantages of using an id over a class would be?

To me, id's seem useless. They can only be used once in each page, when classes are capable of doing everything an id can do and be used as many times as you want!

I understand the difference between the two. I just don't understand the significance of id's.
 

angelwatt

Moderator emeritus
Aug 16, 2005
7,852
9
USA
The fact that the id can only be used once per page gives it a purpose. It lets you clearly divide things up. Having an id of header tells you that's the header and won't be elsewhere too. Within CSS, an id has a higher priority than a class as well so can partially effect how you right your selectors. Within JavaScript, the getElementById function speaks for itself here. I mostly use ids over classes personally.

So essentially you use id for uniqueness and classes for more general classifications.
 

eponym

macrumors 6502
Jul 2, 2010
297
3
IDs have a higher level of specificity than classes in CSS—by a long shot.

This helps to create strong reference points for descendant selectors as well as overrides to generic element rules.

Outside of CSS, IDs have other uses. In forms, in JS and in server-side languages like PHP and ASP. They're also faster to easier to identify in the DOM versus a class.

As an analogy, think of it in terms of families in a neighbourhood. While specifying "boys" vs "girls" is somewhat useful, being able to identify somebody as "John Smith" or "The children of John Smith" in much more so.
 

MOD YOU UPP

macrumors newbie
Original poster
Jul 21, 2010
13
0
Thanks for both of your answers.

I really liked eponym's analogy, that makes a lot of sense.

And I guess I didn't understand classes or id's as well as I thought I did!
 

Dunmail

macrumors regular
Mar 27, 2009
224
4
Skipton, UK
As Angelwatt and Eponym have indicated ids are required for specificity. One way to think of them is part of a hierarchy. From general to specific: (x)html tags then classes then ids.

So as an example, you have a rule for all paragraphs, then override that for the first paragraph following a h2 header using a class rule (though you could also use a descendent rule in this case), then you can override the class rule for a specific paragraph using an id based rule.

Also ids are useful for DOM scripting: you access a specific element using getElementById("yourID").

If you get things right then you should end up with fewer exceptions to your CSS rules.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.