HTML and CSS Reference
In-Depth Information
Figure 3-22
Applying a contextual selector
style rule applied only to h1 headings
nested within section elemen ts
3. Save your changes to the style sheet and then reload the home.htm file in your
Web browser. Verify that the sky blue background is applied only to the Welcome
Attribute Selectors
Selectors also can be defi ned based on attributes and attribute values associated with
elements. Two attributes, id and class , are often key in targeting styles to a specifi c
element or group of elements. Recall that the id attribute is used to identify specifi c ele-
ments within the Web document. To apply a style to an element based on its id, you use
the selector
# id
where id is the value of the id attribute. Thus, to format the text of the h1 heading
<h1 id=”main”>Sunny Acres</h1>
to appear in red, you could apply the following style rule:
#main {color: red;}
Because no two elements can share the same id value, HTML uses the class attribute
to identify groups of elements that share a similar characteristic or property. The attribute
has the syntax
A style rule involving an
id selector has prece-
dence over any rule except
those defined within an
inline style.
< elem class=” className ”> … </ elem >
where className is the name of the element class. For example, the following h1 head-
ing and paragraph both belong to the intro class of elements.
<h1 class=”intro”>Sunny Acres</h1>
<p class=”intro”>
Welcome to Sunny Acres, where there's always
something happening on the farm.
One reason to use the class attribute is to assign the same style to multiple elements
that belong to the same class. A selector based on a class has the form
You can associate a single
element with several
classes by listing each
class name, separated
by a space, as part of the
class attribute value.
. class { styles }
where class is the name of the class and styles are styles associated with that class of
element. Thus, to display the text of all elements belonging to the intro class in blue, you
could apply the following style:
.intro {color: blue;}
Because different types of elements can belong to the same class, you can also specify
exactly which kinds of elements within that class receive the style rule by using the
elem . class { styles }
Search WWH ::

Custom Search