tags:

views:

4959

answers:

22
+10  Q: 

div class vs id

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.

+6  A: 

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.

Mike Farmer
Although this answer is quite good, I think there are better ones down the page -check out Sean McMains and Mecki's answers for example.
Sam Murray-Sutton
+2  A: 

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.

James Curran
A: 

If it's a style you want to use in multiple places on a page, use a class. If you want a lot of customization for a single object, say a nav bar on the side of the page, then an id is best, because you're not likely to need that combination of styles anywhere else.

HitScan
+8  A: 

IDs must be unique but in CSS they also take priority when figuring out which of two conflicting instructions to follow.

<div id="section" class="section">Text</div>

#section {font-color:#fff}
.section {font-color:#000}

The text would be white.

Oli
A: 

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

<div class="code-formatting-style-name" id="myfirstDivForCode">
</div>
Vinko Vrsalovic
A: 

Use an id for a unique element on the page which you want to do something very specific with, and a class for something which you could reuse on other parts of the page.

Sam Meldrum
+22  A: 

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, use id="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'>.

Jim
A: 

The id attribute is used for elements to uniquely identify them within the document, whereas the class attribute can have the same value shared by many elements in the same document.

So, really, if there's only one element per document that's going to use the style (e.g., #title), then go with id. If multiple elements can use the style, go with class.

Mark Cidade
A: 

I would say it is best to use a class whenever you think a style element is going to be repeated on a page. Items like HeaderImage, FooterBar and the like go well as an ID since you'll only be using it once and it'll help prevent you from accidentally duplicating it, since some editors will alert you when you have duplicate IDs.

I can also see it helpful if you're going to generate the div elements dynamically, and want to target a specific item for formatting; you can just give it the proper ID at generation as opposed to searching for the element and then updating its class.

Dillie-O
+15  A: 

The most important thing to understand is that IDs have to be unique: only one element with a given ID should exist within a page. Thus, if you're wanting to refer to a specific page element, that's often the best thing to use.

If you have multiple elements that are in some way similar, you should use the elements class to identify them.

One very useful, surprisingly little known fact is that you can actually apply multiple classes to a single element by putting spaces between the class names. Thus, if you posted a question that was written by the currently logged in user, you might identify it with <div class="question currentAuthor">.

Sean McMains
The additional information here about using multiple classes is especially useful. Nice job including it.
BrewinBombers
+2  A: 

The HTML standard itself answers your question:

No two objects may have the same ID, but an arbitrarily amount of objects may have the same class.

So if you want to apply certain CSS style attributes to a single DIV only, that would be an ID. If you want certain style attributes to apply to multiple DIVs, that must be a class.

Note that you can mix both. You can make two DIVs belong to the same class, but give them different IDs. You can then apply the style common to both to the class, and the things specific to either one to their ID. The browser will first apply the class style and then the ID style, so ID styles can overwrite whatever a class has set before.

Mecki
A: 

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.

thesmallprint
A: 

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.

James Winans
A: 

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.

Toby Mills
A: 

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.

Ken Ray
+1  A: 

Some other things to keep in mind:

  • When using ASP.Net you don't have complete control over the ID of elements, so you pretty much have to use class.
  • 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:

    div.NavArea ul { /* styles go here */ }

Now you can style the logical division for much of your entire navarea with one class application.

Joel Coehoorn
A: 

In addition to id's and classes being great for setting style on an individual item verses a similar set of items, there's also another caveat to remember. It also depends on the language to some degree. In ASP.Net, you can throw in Div's and have id's. But, if you use a Panel instead of the Div you will lose the id.

CodeRot
+2  A: 

An additional benefit to using an ID is the ability to target it in an anchor tag:

<h2 id="CurrentSale">Product I'm selling</h2>

Will allow you to in some other place link directly to that spot on the page:

<a href="#CurrentSale">the Current Sale</a>

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

davebug
A: 

I think we all know what class is, but if you think of IDs as identifiers rather than styling tools, you wont go far wrong. You need an identifier when trying to target something and if you have more than one item with the same ID, you can no longer identify it...

When it comes to writing your css for IDs and CLASSes, it's beneficial to use minimal css classes as far as possible and try not to get too heavy with the IDs until you HAVE to, otherwise you'll constantly be aiming to write stronger declarations and soon have a css file full of !important.

Steve Perks
+3  A: 

Think of University.

<student id="JonathanSampson" class="Biology" />
<student id="MarySmith" class="Biology" />

Student ID cards are distinct. No two students on campus will have the same student ID card. However, many students can and will share at least one Class with each other.

It's okay to put multiple students under one Class title, Biology 101. But it's never acceptable to put multiple students under one student ID.

When giving Rules over the school intercom system, you can give Rules to a Class:

"Would the Biology class please wear Red Shirts tomorrow?"

.BiologyClass {
  shirt-color:red;
}

Or you can give rules to a Specific Student, by calling his unique ID:

"Would Jonathan Sampson please wear a Green Shirt tomorrow?"

#JonathanSampson {
  shirt-color:green;
}
Jonathan Sampson
A: 

Where to use an ID versus a class

The simple difference between the two is that while a class can be used repeatedly on a page, an ID must only be used once per page. Therefore, it is appropriate to use an ID on the div element that is marking up the main content on the page, as there will only be one main content section. In contrast, you must use a class to set up alternating row colors on a table, as they are by definition going to be used more than once.

IDs are an incredibly powerful tool. An element with an ID can be the target of a piece of JavaScript that manipulates the element or its contents in some way. The ID attribute can be used as the target of an internal link, replacing anchor tags with name attributes. Finally, if you make your IDs clear and logical, they can serve as a sort of “self documentation” within the document. For example, you do not necessarily need to add a comment before a block stating that a block of code will contain the main content if the opening tag of the block has an ID of, say, "main", "header", "footer", etc.

Koistya Navin
A: 

Use only classes, never use IDs

alpav
Disagree. (1) IDs have a higher specificity than CLASSes, thus when you want your CSS for a specific single element to trump other styles that may be applied, you want an ID. (2) When using javascript libraries sometimes you want to be able to specify a specific element quickly and efficiently. IDs fit that purpose.
ghoppe