Classes & IDs

A short note on the correct usage of the class and id attributes in HTML.

Shipping Tag by queenbeeamy.

Shipping Tag by queenbeeamy

Given a row with a primary key of 8580 from the car table of a database, the following markup is incorrect:

<div class="car_8580"> … </div>

The HTML5 spec describes the class attribute as:

The [class] attribute, if specified, must have a value that is a set of space-separated tokens representing the various classes that the element belongs to.

Which I read as: “the class attribute should be used for the ‘type’ of an element, and may have more than one type”.

The type of this element is not car_8580, but simply car. The HTML5 spec describes the id attribute:

The id attribute specifies its element’s unique identifier (ID).

The row from the car table would be better marked up as:

<div class="car" id="car_8580"> … </div>

This gives us the “type”, car, and a unique identifier car_8580 for this item. We use the car_ prefix in case there are other types listed in the current document.

Posted on Monday 22nd March, 2010.

The short URL for this post is: http://sneeu.com/s/pBW