CSS - Class vs. Id. Which one should I use?

Conventional wisdom suggests using id for singleton elements, and class for multiple instance elements.

For example, you might use id for your page header and footer, and class for buttons, paragraphs, images, etc.

The problem with this approach is that by reading the HTML alone, it is impossible to tell which items are styled by CSS.

The class attribute can be assumed to always refer to a CSS style.

The situation for id is not so clear.

An element's id could represent:

  • An HTML fragment.
  • A Javascript identifier.
  • A CSS identifier.

A growing number of web developers now recommend:

Use class for all CSS selectors, whether the element is a natural singleton or not.

Reserve the use of id for Javascript identifiers and HTML fragment identifiers.

If you do need to identify a specific instance of a CSS class, then the id selector is appropriate.

Ads by Google

Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath