spacer

ID Selectors

 
ID selectors launch rule sets in embedded or external style sheets that target individual HTML elements. An ID works similar to a class selector except that its style declarations can only be applied to a single HTML element on each web page.

The syntax for ID selectors created in style sheets is simply a "#" sign followed by any name you like. Its style declarations are then applied to the HTML element you wish to target by inserting the id attribute. Hence if you wanted to apply styles to one and only one top level heading element on a web page, you could define the ID in your style sheet as, say, #TopHeading and then you would insert the id="TopHeading" attribute/value pair in an <h1> tag.

The following is an example of a web page using an embedded stylesheet and an ID selector:

Example 2 - AN EMBEDDED STYLE SHEET USING THE ID SELECTOR

<html>

<head>
<title></title>

<style type="text/css">
<!--

#TopHeading {
   font-size: 24px;
   color: navy;
}
-->
</style>


</head>

<body>

<h1 id="TopHeading">'TopHeading' styles apply here only.</h1>

</body>

</html>



So why would I want to use an ID when I could just use a class and make the style declarations reusable in other elements, you may ask?

Well here's a few reasons:
  • IDs allow you to get very specific about which elements your styles are applied to. This is largely a matter of staying organized and can also help a great deal once you start creating more complex CSS selectors.
  • The ID attribute has a distinct advantage over the class attribute in that it automatically creates the equivalent of a named anchor that can be targetted with a hyperlink using a fragment identifier... (*chuckle*... yeah okay that was a lot of techno-speak there...)

    Let's put that another way. Using the above example, the h1 element using an id="TopHeading" attribute/value pair can be targetted with the following hyperlink:


    <a href="#TopHeading">Go to heading...</a>


  • Once you start breaking into Javascript and DHTML, you'll see how using ID selectors can help create dynamic web page effects.
However, until you find your bearings with CSS, you should mainly stick with class selectors.


*   *   *


However, before you start writing up a bazillion classes (and IDs) to target every last HTML element on your web page, you'll want to know how to combine selectors to make for more advanced targetting possibilities.


SEE ALSO: