A common mistake I see many beginning web designers make is deciding when to use a .class and when to use an #ID. The best way to explain it is: classes can be used many times while IDs can only be used once per page.

A real world example might be your website's template. Look at the code below that I stripped down to just the layout elements of a website's template:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head></head> <body> <div style="text-align:center;" class="mass"> <div class="logoBar"> <div class="sqLogo"></div> <div class="locator"></div> </div> <div class="navBarTop"> <ul id="nav"></ul> </div> <div id="navBarBorder"></div> <div class="mainCopy"> </div> <div class="tagLineBox"></div> <div class="footerBox"> <div class="alsLogo"></div> <div class="footerNavBox"></div> <div class="100yearLogo"></div> </div> </div> </body> </html>

For structural elements like all of the elements above, IDs should be used and not classes. Classes are best used for text related elements or really anything that you might use more than once on a webpage. IDs should be used for unique elements that will only appear once in the DOM. Also remember that classes can be combined while IDs cannot:

<div class="bold italic">Hello World!</div>

Using a HTML ID More Than Once

On the flip side NEVER use the ID attribute more than once. The reason for this is the ID attribute has other meanings within HTML such as:

  • Referencing the element with JavaScript through the getElementById DOM method
  • Making the element an anchor which can be linked to with a fragment identifier
  • Associating a label element with a form control via the for attribute
  • Specifying which header cell(s) that provide header information for a data cell via the headers attribute

Credit: this list was taken from Roger Johansson's website.

Overuse of Classes and IDs

Another problem I see, is web designers overusing classes and IDs. Consider the following:

<div class="navBarTop"> <ul id="nav"></ul> </div>

Notice that the UL tag contains an ID? Unless it's being used by JavaScript or there is an anchor pointing to it there's really no reason to place the ID attribute on it. The element could be selected via CSS with .navBarTop #navBarTop ul which essentially renders the ID attribute useless. Don't litter your HTML with redundant attributes.

When Is the Best Time to Fix These Problems?

The best time to hunt down redundant attributes and incorrect usage of classes vs IDs is during the initial development of a website. Once the site has been in production for awhile it is harder to hunt down whether that ID tag is needed anymore or to have to update your template file and CSS file so that you are using IDs rather than classes.