An ID selector in CSS is much like a tag-specific class in that it is an exclusive club. It's so exclusive, in fact, that it applies to one and only one element per page. No two elements should belong to the same ID, even if the elements are of the exact same type: paragraphs, headings, images, links, or what have you. To define an ID selector, you use special syntaxnamely, the number sign (#), followed by the name of the ID: #barney { font-weight: bold; color: #FF00FF; }
Then, set the id attribute of the tag to which you want to apply the style: <p >This paragraph has the ID of "barney."</p> IDs come in handy as substitutes for style rules that appear in the style attribute of an HTML tag. You'll recall that putting CSS code in the style attribute works best for one-off styles. What is an ID if not a one-off style? So feel free to replace something like this: <p style="font-weight: bold; color: #FF0000;">Alert!</p> with something like this: <style type="text/css"> #alert { font-weight: bold; color: #FF0000; } </style> <body> <p >Warning!</p> </body>
As you can see in Figure 58.1, both methods have the exact same effect. If you're a coding aesthete, the ID method may be a bit cleaner, a bit tastier to your palette, and a bit more authentic to the spirit of CSS. You'd probably rather use an ID than shove the style rule into the attribute of some clunky old HTML tag, although either method gets the job done. Figure 58.1. An ID style (top) works just like the style attribute of an HTML tag (bottom) in that it defines a one-off style rule. The effects are identical. |