When using divs when is it best to use a class vs id?
Is it best to use class, on say font variant or elements within the html? Then use id for the structure/containers?
This is something I've always been a little uncertain on, any help would be great.
IDs should be unique. CLASSes should be shared. So, if you have some CSS formatting that will be applied to multiple DIV, use a class. If just one (as a requirement, not as happenstance), use an ID.
My flavor of choice is to use class identification when css styles are applied to several divs in the same way. If the structure or container is really only applied once, or can inherit its style from the default, I see no reason to use class identification.
So it would depend on whether your div is one of several; for instance, a div representing a question to an answer on the stackoverflow website. Here you would want to define the style for the "Answer" class and apply this to each "Answer" div.
Classes are for styles you may use multiple times on a page, IDs are unique identifiers that define special cases for elements. The standards say that IDs should only be used once in a page. So you should use classes for when you want to use a style on more than one element in a page, and an ID when you just want to use it once.
Another thing is that for classes you can use multiple values (by putting spaces in between each class, a la "class='blagh blah22 blah') wheras with IDs, you can only use on ID per element.
Styles defined for IDs override styles defined for classes, so in , the style settings of #uniquething will override the style of .whatever if the two conflict.
So you should probably use IDs for things like, the header, your 'sidebar' or whatever, and so on - things that only appear once per page.
As well, an element you give a specific id to can be manipulated via JavaScript and DOM commands - GetElementById, for example.
In general, I find it useful to give all of the main structural divs an id - even if initially, I don't have any specific CSS rules to apply, I have that capability there for the future. On the other hand, I use classes for those elements that could be used multiple times - for example, a div containing an image and caption - I might have several classes, each with slightly different styling values.
Remember though, all things being equal, style rules in an id specification take precedence over those in a class specification.
Some other things to keep in mind:
It's best to use neither, when you can help it. Instead, specify the element type and it's parent's type. For example, an unordered list contained inside div with the navarea class could be singled out this way:
Now you can style the logical division for much of your entire navarea with one class application.
For me : If use classes when i will do something in CSS or add name to elements and can use in all elements in a page.
So IDs i use for unique element
Ex :
CSS :