Face Off - Class v. ID
November 21st, 2007What is the difference between a class and an ID in CSS? Both seem to behave identical, but they have different uses. A good coder knows when and how to use each one.
IDs:
- Can only be used once on a page
- Can be used with a class for the same element
- Used to identify one and only one specific element
Classes:
- Can be used several times on a page
- Can be used with other classes and IDs
- Reusable and can be applied to any element on a page
So what is this big who haw? If you have tried to use an ID multiple times I’m sure that you have noticed it works. Well the who haw is that it is not valid. This gets us into another discussion which is the importance of valid code, but for now we will hold off on that.
– Lets break it down. The only difference between a class and an ID is that a class can be reused and an ID cannot. –
Both classes and ID can use numbers, letters and some special characters, like an underscore. But be careful here. Upper case characters and lower case are different characters. Some browsers will be forgiving and treat “a” and “A” the same, but some will not and here you will run into problems. So be sure that your tags are identical.
Where did these names come from?
This will hopefully help you remember the purpose for each. A person’s ID is unique and individual to them. A class is made up of many people. bring this back to coding for the web. An element, for example one specific paragraph on a page, can have an ID unique to it. Also it can have a Class that it will share with all of the paragraphs on that page.
No Responses to “Face Off - Class v. ID”