HTML & CSS
I am new to CSS. I was going through many references but none of them made me understand the difference between id and class. I saw many css files but couldn't figure when they are used and when they must be avoided. Could you please explain me in detail?
Hi ankur218. Classes and IDs are both hooks for CSS styling. That is, if you put either on an element, you can then style that element by targeting the class or ID. In a way, it doesn't matter much which you use, but be aware of a few things:
- you can only use the same ID once per page, while you can re-use a class on a single page as many times as you like
- an ID 'carries more weight' than a class, which can be good or bad. This is an issue of specificity
- you can place multiple classes on an element (very handy) whereas you can only have one ID per element.
Also, IDs are handy for a few other things, such as:
- same-page links. (You can reference an ID in a link and the browser will jump to the element with that ID)
Hope that helps.
Welcome to the site. ralph.m has got you covered there, I have been learning on and off for about two years now. Two things that have helped me a lot
The css tutoriasl on that site are really good, but I knew css a fair bit (basics) when I started the course. they cover a bunch of other things. Also, get a good book, it is helpful to learn through a book as well as on the web. I really got a lot out of developing with web standards by John Allsopp.
I should add that sitepoint has so great refrences + examples where you can try you code as you learn. TBH it's just as good if not better than my other example, but they both have diffrent aspects. Codecademy has a game aspect which is really cool.
Also this is the best way to learn about specificity IMO.
ralph.m. thanks a lot for your explanation. I am kind of cleared with my doubts. Will get it done completely after I start playing around. But I have this doubt, if id can be used only once per page then why can't we use only class everywhere?
unconformed. Yeah bro, I am learning from codeacademy only. Specificity is something I have to pay attention too. I took it very lightly while learning a year back. This time I shall learn properly. And also, I will refer the references you have mentioned.
Thanks a ton both of you
Once per page is not quite right. Once "in" an HTML document. You can, of course, use the same ID on every page. You can also just use classes, you're not forced to use IDs except for certain form elements.
Page ... document ... meh. :lol:
LOL, kind of similar. I mean, if one HTML document is applicable to say 3-4 pages, oh yeah, I am wrong
I think I came across as pedantic, which I didn't mean to. You mentioned you still had doubts after Ralph's explanation, so I attempted to clarify.
This topic is now closed. New replies are no longer allowed.