HTML and CSS Reference
In-Depth Information
It's possible to add even more expression to selectors and to apply styles in a way that
cuts across elements in favor of types of information. Of course, to get something so
powerful, you'll have to do a little work in return, but it's well worth it.
Class and ID Selectors
So far, we've been grouping selectors and declarations together in a variety of ways,
but the selectors we've been using are very simple ones that refer only to document
elements. They're fine up to a point, but there are times when you need something a
little more specialized.
In addition to raw document elements, there are class selectors and ID selectors , which
let you assign styles in a way that is independent of document elements. These selectors
can be used on their own or in conjunction with element selectors. However, they work
only if you've marked up your document appropriately, so using them generally in-
volves a little forethought and planning.
For example, say you're drafting a document that discusses ways of handling pluto-
nium. The document contains various warnings about safely dealing with such a dan-
gerous substance. You want each warning to appear in boldface text so that it will stand
out. However, you don't know which elements these warnings will be. Some warnings
could be entire paragraphs, while others could be a single item within a lengthy list or
a small section of text. So, you can't define a rule using element selectors of any kind.
Suppose you tried this route:
p {font-weight: bold;}
All paragraphs would be bold, not just those that contain warnings. You need a way
to select only the text that contains warnings, or more precisely, a way to select only
those elements that are warnings. How do you do it? You apply styles to parts of the
document that have been marked in a certain way, independent of the elements in-
volved, by using class selectors.
Class Selectors
The most common way to apply styles without worrying about the elements involved
is to use class selectors. Before you can use them, however, you need to modify your
actual document markup so that the class selectors will work. Enter the class attribute:
<p class="warning">When handling plutonium, care must be taken to avoid
the formation of a critical mass.</p>
<p>With plutonium, <span class="warning">the possibility of implosion is
very real, and must be avoided at all costs</span>. This can be accomplished
by keeping the various masses separate.</p>
To associate the styles of a class selector with an element, you must assign a class
attribute to the appropriate value. In the previous code, a class value of warning was
 
Search WWH ::




Custom Search