ID selectorsExplanationID 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. SyntaxAs 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 ID selectors that apply only to a particular type of element (for instance only headings of level one or paragraphs) have the syntax 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. UseI'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, 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, To select this h1 then you would use the selector 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 supportDetailed 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(C)1997-2001 Western Civilisation Pty. Ltd. |