CSS CSS Basics (2014) Basic Selectors Reusing Classes

Why we use ID

I know IDs have more weight then classes. But I wanted to know in which specific scenarios we need to use IDs?

5 Answers

Josh Sneddon
Josh Sneddon
15,943 Points

I like to keep the functionality and presentation of my code separate, so I recommend using IDs for fragment identifiers and JavaScript hooks and classes for your styling. The benefits of this approach are that classes are more versatile because they can be reused, this makes your code more modular. Using IDs and classes for separate purposes avoids any potential specificity issues and makes your code easier to understand by another developer, which is important if you're working as part of a team.

Thomas Workman
Thomas Workman
7,173 Points

Classes are used for global attributes, however, I recommend to all that you avoid using ID's, unless it is absolutely necessary. You can still achieve the same desired styling using a class without running into specificity issues later with ID's. You don't want to be putting ID's on everything to get your styles to come to life. Using classes will make your code much easier to work with, especially as your app grows. My two cents anyway, take it for what it's worth or don't.

Maxwell DeMers
Maxwell DeMers
6,853 Points

In my experience, IDs are used when you want to specify something for styling purposes, if only one element should be styled that way. You can have several elements with the same class, but may want just one of them to be a little different. That is when I use IDs.

Let me know if you'd like more specifics.

Andrea Gomez
Andrea Gomez
8,609 Points

Would it like... Let's say a Blog, the title of the Blog could use an ID because it'll be displayed and used only once however, the titles for each Blog entry would use a class because you're going to have multiple articles that'll have the same presentation, right?

Idan Melamed
Idan Melamed
16,280 Points

I think you have to use ID's when creating html forms

Alex Flores
Alex Flores
7,864 Points

This is the way I understand it and so far, it's been working well for me. Classes are, so to speak, css global attributes. That is, they can be used in any element and are very versatile. IDs are not. IDs are best used for manipulating specific elements via JS or CSS.