Brought to you by Style Master CSS editor

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 have 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-name#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.

Note that an ID comprises only alpha numeric characters, and hyphens. They cannot include underscores and other characters, nor spaces. An ID cannot begin with a numeral.

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 might use them.

We saw in the section on class selectors that HTML 4.0 introduced the class attribute. HTML elements can have classes, and to give an element a class, you add the attribute class to the opening 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">. Note that in any valid HTML document there should only be one heading 1 with an ID of title.

To select this h1 then you would use the selector h1#title.

The ID attribute and selector will probably remain pretty redundant for most of us. It is hard to see what you would do with it that you can't do with a simple old class selector.

Browser support

Detailed browser support information for this feature can be found in the full version of the Westciv CSS Guide, or in our CSS Browser Support Table.

next: contextual selectors