HTML and CSS Reference
In-Depth Information
The following markup shows how a green background is applied to the
<p>
tag with
the
id
value of "
p2
", whereas no style is applied to the other paragraphs:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>
Id Selector Example
</title>
<style type="text/css" media="all">
#p2 {background-color: green;}
</style>
</head>
<body>
<p>
This is the first paragraph.
</p>
<p id="p2">
This is the second paragraph.
</p>
<p>
This is the third paragraph.
</p>
</body>
</html>
O
NLINE
http://htmlref.com/ch4/idselector.html
As a core (or global) attribute, the
id
attribute is common to nearly all (X)HTML
elements. However, given widespread use of
id
attributes, page authors need to be very
careful to ensure that elements are named uniquely. Developers must not name two
elements the same name using the
id
attribute. If two of the paragraphs have
id="p2"
,
what will happen? In the case of most browsers, both paragraphs will show up green.
However, this is such sloppy style that it generally will result in significant errors once
scripting is added to the document. Furthermore, the document will not validate with such
mistakes. If multiple elements should be affected in a similar way, use a class rule instead.
Element-Specific id Rules
One nonintuitive variation of an
id
selector is an element-specific selector like
p#p2 {background-color: green;}
This would select only paragraph elements with their
id
attribute set to
"
p2
.
"
Compare this
to a rule like
#p2 {background-color: green;}