Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,736 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.