cascading style sheets tutorial

ID Selectors

Explanation

ID selectors are a lot like class selectors. They work in a very similar way, and have a similar syntax. The essential difference is that while class selectors apply to one or more elements on a page, ID selectors apply to exactly one element.
For example, while you can have many lists of ingredients, you might have only one main title.

ID selectors are not widely used, so you needn't worry yourself particularly about why they exist. If you ever find yourself with unique elements, you can use the ID selector to select them in a statement.

Syntax

As just noted, the syntax for the ID selector is much like that for the class selector. Again there are two kinds of selector, those associated with a particular type of element, and the more general selector that can apply to any element with an ID that matches the ID of the selector. We'll see shortly what it means for an element to have an ID.

ID selectors that can apply to any type of element has the simple syntax #idname, for example, #title. This selector selects the single element on a page that has an ID of title.

ID selectors that apply only to a particular type of element (for instance only headings of level one or paragraphs) have the syntax element#idname, for example H1#title. This selector selects the single heading of level 1 with an ID of title. It will not select any other element with that ID, nor will it select any other headings of level 1.

Use

I've already mentioned that ID selectors are not commonly used. Many people scratch their heads and wonder why they are needed at all. I'll pass on that question as the answer would probably bore you. But for completeness, let's look at how you would use them in conjunction with your web page.

We saw with classes that HTML 4.0 introduced class attribute. HTML elements can have classes, and to give an element a class, you add the attribute class to the tag for that element like this, <P class="introduction">. Ids are very similar.
HTML 4.0 introduced the ID attribute, which is given to an element in a very similar way, by adding the ID attribute to the element tag. For example, to give a heading an attribute of title, you use the following tag, <H1 ID="title">.