HTML and CSS Reference
In-Depth Information
which would match any element with an
id
of
"p2
.
"
Immediately, you should think that
this implies that more than one element can share
id
values—why else would we need to
be more specific than a simple
id
rule? Well, within a single document, that is correct, and it
is not appropriate to have markup like
<p id="p2">
I am a correctly identified paragraph
</p>
<div id="p2">
Wait you already used that id value!
</div>
<p>
Not
<span id="p2">
again!!!!
</span>
You already used the value p2!
</p>
and then use style rules like
p#p2 {color: red;}
div#p2 {background-color: blue; color: white;}
span#p2 {color: blue;}
However, such rules would make sense if this were a linked style sheet used site-wide
and we had different elements in different documents all named
"p2
.
"
The author considers
such usage bad style as it assumes that page content is always found within the same
document and will never move, which is not always the case. A site-wide unique
id
approach would solve such future problems and would alleviate the need for this type of
selector.
class Rules
The
class
attribute is used to define the name(s) of the class(es) to which a particular tag
belongs. Unlike
id
values,
class
values don't have to be unique because many elements
can be members of the same class. In fact, elements don't even have to be of the same type
to be in a common class. Writing rules for classes is easy: simply specify the class name of
your own choosing, such as “nature,” with a period before it as the selector:
.nature {color: green;}
The use of
class
is illustrated here:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>
Class Selector Example
</title>
<style type="text/css" media="all">
.veryimportant {background-color: yellow;}
</style>
</head>
<body>
<h1 class="veryimportant">
Example
</h1>
<p class="veryimportant">
This is the first paragraph.
</p>
<p>
This is the second paragraph.
</p>
<p class="veryimportant">
This is the third paragraph.
</p>
</body>
</html>