HTML and CSS Reference
In-Depth Information
Using Attribute Selectors
• To apply a style based on the id value of an element, use the
#
id
selector, where
id
is
the value of the
id
attribute.
• To apply a style based on the class value of elements, use either the
.
class
or the
elem
.
class
selectors, where
class
is the value of the
class
attribute and
elem
is
the element name.
• To apply a style based on whether an element contains an attribute, use the
elem
[
att
]
selector, where
class
is the class name and
att
is the attribute name.
• To apply a style based on whether the attribute value for elements equals a specified
value, use the
elem
[
att
=”
val
”]
where
val
is the specified value.
In the Sunny Acres home page, Tammy has added the following
class
attribute to the
last paragraph that introduces the Web site:
<p class=”closing”>We all hope to see you soon,
down on the farm.<br />
— <span>Tammy & Brent Nielsen</span>
</p>
She suggests that you format this paragraph so that it appears in green and is right-
aligned on the page. To do this, you'll add the following style to the
sa_styles.css
style
sheet:
section p.closing {
color: rgb(0, 165, 0);
text-align: right;
}
Note that this style rule applies to paragraphs belonging to the closing class and
nested within the
section
element. You could have simply used the
.closing
selec-
tor, but then the style rule would apply to any element belonging to the
closing
class.
Usually, you want to be as specifi c as possible in your style sheet so that you are always
targeting exactly the elements that you want to target.
To create a style based on the
class
attribute:
◗
1.
Return to the
sa_styles.css
file in your text editor.
◗
2.
Add the following style rule at the bottom of style sheet (see Figure 3-24):
/* Section styles */
section p.closing {
color: rgb(0, 165, 0);
text-align: right;
}
Figure 3-24
Applying a selector based on class
display the
text in
green and right-aligned
style rule for paragraphs in t
he closing
class nested within a section element