Hi Devendra

Devendra Shrikhande wrote:
What is the advantage of the fact that IDs must be unique on a page? I am aware of the circumstance that if you need to "repeat" an ID, set is as a class, but have still not figured out the advantage of an ID.

This is an important topic. At first glance, it would seem that there is little need for an id attribute - why not use classes everywhere?


However, there's a semantic difference between ids and classes, which is this: it's basically the difference between individuals and groups.

An id identifies a specific individual element of the document markup and allows CSS to be written that addresses that element specifically. In addition, you can reference the id in DOM (Document Object Model) scripting to access an element using the getElementById() function.

A class, on the other hand can apply to many elements, not necessarily of the same type - you could have a class called "warning" that is applied to <h1>, <p>, <li> and so on to emphasize a warning condition, for instance. Another example (which is pertinent to the thread that you came in on) is where you want a class to clear floats. It may be that you need to apply that class on more than one occasion in a particularly fluid layout. By creating a "clearer" class you can apply it to any appropriate block element in order to clear the preceding floats.

Another thing to bear in mind is that ids have higher precedence than classes in determining what style is applied to a given element. This means that

#myid {
  color: blue;
}
.warning {
  color: red;
}

will colour the element

<p id="myid" class="warning">Hello!</p>

in blue (despite the fact that the .warning directive appears later in the CSS cascade).

(To ensure that it's red you would need to add
#myid.warning {
  color: red;
}
to your stylesheet).

If you carefully lay out your document, with ids for all the main display blocks, you can set global class styles and then override them on a block-by-block basis via the blocks' ids. So, for instance it might be appropriate to display elements with the "warning" class differently in a main "content" block as opposed a "summary" block.

Eric Meyer covers this topic well on pages 36-38 of his Cascading Stylesheets The Definitive Guide 2nd Edition.

Having said all that, be wary of overusing ids and classes. By using CSS selectors carefully, a lot of unnecessary "classitis" can be avoided.

Hope that helps
Peter

******************************************************
The discussion list for  http://webstandardsgroup.org/

See http://webstandardsgroup.org/mail/guidelines.cfm
for some hints on posting to the list & getting help
******************************************************



Reply via email to