Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

CSS

William Safstrom
William Safstrom
1,203 Points

Different between ID and CLASS

I think I missed when he described the different between ID and CLASS. What's the different? When should you use one before the other?

2 Answers

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,696 Points

There should only be one element with an id. There can be many elements that share the same class. So a good use for an id would be something like a modal window, where you only want one. If you have a lot of buttons on my page, and you want them to all be similar, you could give all the buttons the same class.

Robert Bailey
seal-mask
.a{fill-rule:evenodd;}techdegree
Robert Bailey
UX Design Techdegree Student 5,089 Points

IDs have a high specificity; specificity simply means that the browser is deciding which CSS property values are most relevant or important to a certain element. In order to overwrite the styles that belong to the ID, you must either write a new ID or use the !important within your code block (CSS) which isn’t always recommended in certain cases.

IDs are unique; this simply means that if you attach styles to an ID, you cannot and won’t be able to reuse it within the same webpage. The ID selector is used for selecting a single HTML element (footer, header, menu etc). On the other hand, classes can appear on many different elements on the same page. Classes are used for single and multiple elements and appear on a page more than once (links, buttons etc). Being able to reuse code (classes) that we have created is very beneficial within HTML. Keep in mind that an element can have both an ID and class.

Readability; since classes and IDs have clear purposes, it makes it a lot easier on the developers when deciding on which selectors to use. Since IDs are unique and have a high specificity, (in some cases) other developers pay attention to the element that has IDs to understand the purpose or function of that element.

Limiting; IDs limit you, whereas classes allow flexibility. You will begin to notice these flexibilities as time goes on.