treehouse : what would you like to learn today?
Web Design Web Development iOS Development

pros and cons of using all Classes and no IDs?

  • Just joined the forum, so forgive me if this is an old debate, but while I do understand the differences between using an ID and a Class in CSS, I was wondering if there are any opinions about using ALL classes and no IDs.

    If you have multiple divs with the same class, to style them differently, you can give the second one a second class that supersedes the first class, so I'm not seeing any real reason not to use all classes.

    Is there any reason that scripts would use IDs over classes?

    -Michael
  • You can use a class as many times as you want, you can assign more than one class to an element - so the options are limitless, especially for specific styling.

    ID's are unique to the page, or should be. Brilliant for setting up a page structure like "wrap" or "footer" whatever, then using classes within that. Classes are also awesome when used in jQuery to add styles to elements, to mark an element after an event has taken place etc... etc...

    Without classes you are stuck with unique ID's, and for specific "non-important" element targeting, and vice versa really...

    In scripts like jQuery ID's don't have to be "found" like classes - athough jQuery does a good job at finding classes... I dont really get how that works any differently.

    ID's and Classes both fill an important role though.
  • That's a great question. I think the biggest factor is speed. JavaScript can find an element on a page by ID far faster and easier than it can with classes, and in fact, native JavaScript doesn't even have a getElementByClass, only getElementByID. Probably most importantly though is that ID's act as page anchors. So if you have a <h2 id="comments">, you can have a <a href="#comments">jump to comments</a> which jumps down to that area. Classes can't do that, and it's quite useful.
  • Ahh so jQuery actually does find the class - I always wondered what the difference there was :)
  • Thanks Chris, that's a big difference.