Applying Styles to IDs

ID attributes can be assigned to any tag. The example below shows a <p> tag and an <a> tag with id attributes:

<p id="first_paragraph">Here is my paragraph. It has a link to 
<a href="http://www.gmu.edu" id="gmu">George Mason University.</a></p>

The name of the id is completely up to you. It doesn't matter what you call the id. You could call it "horseradish" or "red_balloon_number_5" if you like. Usually it makes sense to choose names that make sense in the context of the page, though. When naming id attributes, you should observe these rules:

In your style sheet, you can create a style for a tag with an id by using the pound sign ( # ) and the name of the id, like this:

#first_paragraph { 
  background-color: white;
  color: black;
  }

#gmu {
  background-color: green;
  color: yellow;
  }

I will re-emphasize that you can have only one id per page with any given name. You can only have one tag with the id of "first_paragraph" and only one tag with the id of "gmu".

Question: If you can only have one item with any given id per page, is the id method very useful at all?

Answer: Actually, yes, it is very useful. Most styles on most web sites can be applied either directly to tags or to items with specific id attributes. This is because you can set the global styles (e.g. for all paragraphs) using styles applied to tags and as far as the rest of the items are concerned, most designs have only one of each item. For example, there is usually only one main menu in a web site design (often a list of links across the top of the page). There is usually only one site logo (often in the upper left hand corner). There is usually only one main content area, one footer (with links to copyright info or contact info), and perhaps one side menu. Given the fact that there is only one of each, it makes sense to use the id technique in these cases.

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 License.