Chapter 58. Defining ID Styles


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; } 

GEEKSPEAK

An ID selector is a selector that applies to one and only one element per page.


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> 

FAQ

What happens if I apply the same ID to more than one element?

You won't go to prison, and your computer won't explode, and you won't crash the Internet. The browser treats IDs like classes, so, if you do happen to use the same ID for multiple elements, all the elements appear with the ID style.

However, you create all kinds of problems for yourself when it comes time to add JavaScript functions to your page that use the getElementByID method. If your IDs are not unique, your functions won't work properly.

So, if you want a class style, create a class style. Reserve IDs for special classes of one.


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.




Web Design Garage
Web Design Garage
ISBN: 0131481991
EAN: 2147483647
Year: 2006
Pages: 202
Authors: Marc Campbell

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net