Skip to main content

class (HTML attribute)

By Adam Roberts

HTML & CSS

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Description

While the name of an element specifies its type, the class attribute lets you assign to it one or more subtypes. These subtypes may then be used in CSS code for styling purposes, or by JavaScript code (via the Document Object Model, or DOM) to make changes, or add behavior, to elements belonging to a particular subtype.

Note that the class attribute cannot be applied to the following elements:

  • base
  • basefont
  • head
  • html
  • meta
  • param
  • script
  • style
  • title

Value

This attribute takes as its value a space-delimited list of one or more class names. Unlike the id attribute, the class attribute’s value may begin with a number and will still be valid HTML; for example, <div class="3-col-wide"> … </div>. However, it’s best avoided as the CSS 2.1 specification says that CSS identifiers, which would include the class name that matches the class attribute in the HTML, should not begin with a digit. By not starting class names with a digit, you’ll be keeping both HTML and CSS validators happy.

While there have been numerous calls from the developer community to specify a standard set of class names and associated meanings, at the moment you’re free to specify whatever class names make sense to you. As with all HTML markup, however, it’s recommended that you use names that are as semantically meaningful as possible; the class name should indicate to a human who reads it what that element’s purpose or meaning is, rather than how it looks. Hence, purely presentational class names like “large” or “shiny” are bad practice, while class names such as “executive-summary” or “key-findings” provide some useful information to those reading the markup.

While it’s good to make the markup human-readable, the developer community has made great strides in standardizing the usage of class names for certain types of information on the Web, such as contact details or calendar events, so that the markup can also be read, or parsed, by web-based services to great effect. The result of this standardization effort is known as Microformats.

Adam is SitePoint's head of newsletters, who mainly writes Versioning, a daily newsletter covering everything new and interesting in the world of web development. He has a beard and will talk to you about beer and Star Wars, if you let him.

New books out now!

Get practical advice to start your career in programming!


Master complex transitions, transformations and animations in CSS!