Previous Page
Next Page

Checking Your ID

Along with rules based on tags and classes, there's another type of selector called id. An id is a unique identifier that allows you to be specific in your formatting. You can apply both a class and an id at the same time, as shown in Script 11.5. This allows you to both use the formatting for the class and augment it with the more-specific id formatting that you've defined. If you prefer, you can also use an id selector by itself, without a class.

Script 11.5. Applying an id selector to the style.

body {
     background-color: white;
     color: black;
     font-family: "Trebuchet MS", verdana, helvetica, arial, sans-serif;
     font-size: 0.9em;
}
img {
     margin-right: 10px;
}
.character {
     font-weight: bold;
     text-transform: uppercase;
}
div.character {
     margin: 1.5em 0em 1em 17em;
}
.directions {
     font-style: italic;
}
.dialog, .directions {
     margin-left: 22em;
}
#week2 {
     background-color: #FFFF00;
}

When an id is used, it's because you need a unique way of identifying a particular object on a page. You've seen ids used throughout this book, as ids are also how JavaScript knows which precise object on the page to manipulate.

In this example, a teacher wants to assign a particular character's speech to the students to translate into modern language and so, gives a unique id to each speech. In order to highlight a particular section, all the teacher has to do is to change the id of the selector within the style tag.

To add an ID to your style sheet:

1.
#week2 {
  background-color: #FFFF00;
}



This rule creates a selector named week2. Any area that uses this rule will have a background color of yellow (yellow has a hex value of #FFFF00). Note that id selectors must be defined with a leading # character.

2.
<div class="dialog" id="week2">



You'll find this line in Script 11.1. The text inside this <div> tag uses both the class "dialog" and the id "week2". This causes both rules to apply. If they conflicted with each other, the id would take precedence.

Tips

  • As shown in Figure 11.5, the background color is changed not just behind the text, but all the way over to the right margin. If you want just the background behind the text to be changed, you'll want to use a <span> instead of a <div>.

    Figure 11.5. This CSS changes the background color of the id selector; the colored bar extends across the width of the page.

  • Another way to define a color such as #FFFF00 is as #FF0. Because the hex characters are repeated, the shorthand version is equivalent and gives the same results.



Previous Page
Next Page