IDs & Classes

IDs and classes are both types of HTML attributes that can be used to give a name of your choice to HTML elements. These names can be used as targets for CSS selectors, as targets for anchor links, or as targets for javascript functionality.

Usage Rules

Like any other HTML attribute, IDs and classes are placed inside the opening tag for a given HTML element and follow standard attribute syntax. ID and class names should be written in all-lowercase and with dashes instead of spaces.

IDs

What distinguishes an ID from a Class is that a particular ID can only be used once per page. IDs also have a much higher level of specificity as a CSS selector (it wins in a fight with a Class). As such, IDs shouldn't be used at all for CSS, and should only be used with great care otherwise.

Instead, IDs are best used as targets for anchor links or as targets for javascript functionality.

Classes

Classes, on the other hand, can only be used an unlimited number of times per page, on as many elements as you like. They are also the preferred way of naming elements for use in CSS.

Classes should be given names that describes the general role of the content they contain. They should never be named to reflect the style or layout CSS they will be used to apply. This causes a breakdown of the separation between HTML and CSS and can lead to all sorts of problems.

A good rule of thumb for naming classes is to make them nouns.

Imagine you name a class "red-background" and use it to apply a red background-color. Then later you decide to redesign your site to have a blue background. It's too much work to go into every HTML document and change the class name, so you simply change the style applied in the HTML. Now you have a class named "red-background" that is used to apply a green background-color. Not very sensible, is it?

Multiple Classes or IDs

Multiple Classes or IDs can be applied to a single element by space-separating them within the quotation marks of the attribute.

Practice Exercise

Resource Links