Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

164 LESSON 8: Using CSS to Style a Site


In this case, if a <p> tag is has the class imprtnt, the text inside will be blue. If a <div>
has the imprtnt class, its text will be red. You could also rewrite the preceding two rules
as follows:
.imprtnt { font-weight: bold; }
div.imprtnt { color: red; }
p.imprtnt { color: blue; }

All members of the imprtnt class will be bold and <div> tags with the class imprtnt will
be red, whereas paragraphs with the class will be blue. If you assigned the imprtnt class
to another tag, like <li>, the default color would be applied to it.
Whenever you want to specify styles for a single element, assign it an ID. The element
must be unique on the page—the only element with that identifier. As you’ll learn later
in the book, assigning IDs to elements is also very useful when using JavaScript because
doing so lets you write scripts that reference individual items specifically. For now,
however, let’s look at how IDs are used with CSS. Generally, a page will have only one
footer. To identify it, use the id attribute:
<div id="footer">
Copyright 2010, Example Industries.
</div>

You can then write CSS rules that apply to that element by referencing the ID. Here’s an
example:
#footer { font-size: small; }
As you can see, when you refer to IDs in your style sheets, you need to prepend a # on
the front to distinguish them from class names and element names. Note that there’s no
additional facility for referring to IDs that are associated with particular elements. IDs are
required to be unique, so there’s no need to qualify them further. Finally, there’s nothing
to say that you can’t mix up all these selectors in one rule, like so:
h1, #headline, .heading, div.imprtnt { font-size: large; color: green; }
As you can see, I’ve included several types of selectors in one rule. This is perfectly valid
if you want to set the same properties for a number of different selectors. Classes also
work with contextual selectors:
ul li.important { color: red; }
In this case, list items in the imprtnt class will be red if they occur in an unordered list.
If they’re in an ordered list, the rule will not be applied.
Free download pdf