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.
If you are using .Net web controls then it is sometimes a lot easier just to use classes as .Net alters web contol div id's at run time (where they are using runat="server").
Using classes allows you to easily build up styles with separate classes for fonts, spacing, borders etc. I generally use multiple files to store separate types of formatting information, e.g. basic_styles.css for simple site wide formatting, ie6_styles.css for browser specific styles (in this case IE6) etc and template_1.css for layout information.
Which ever way you choose try to be consistent to aid maintenance.
An additional benefit to using an ID is the ability to target it in an anchor tag:
Will allow you to in some other place link directly to that spot on the page:
A common use for this would be to give each headline on a blog a datestamped ID (say id="date20080408") which would allow you to specifically target that section of the blog page.
It is also important to remember that there are more restricted naming rules for ids, primarily that they can't start with a number. See similar SO question: What is a valid value for id attributes in html
classes are great when you want to apply similar styles to many different divs or elements. ids are good when you want to address a specific element for formatting or for updating with javascript.
id is supposed to be the element unique identifier on the page, which helps to manipulate it. Any externally CSS defined style that is supposed to be used in more than one element should go on the class attribute
Use
id
to identify elements that there will only be a single instance of on a page. For instance, if you have a single navigation bar that you are placing in a specific location, useid="navigation"
.Use
class
to group elements that all behave a certain way. For instance, if you want your company name to appear in bold in body text, you might use<span class='company'>
.IDs must be unique but in CSS they also take priority when figuring out which of two conflicting instructions to follow.
The text would be white.