Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Understanding selectors, specificity, and cascading CHAPTER 4 153


FIGURE 4-2 All subsequent <h1> elements background color set to yellow

Using an attribute selector
An attribute selector selects elements based on the existence of the specified attribute. For
example, a[title] selects all hyperlinks whose title attribute is defined.
The following example demonstrates the use of an attribute selector to locate all hyper-
links whose href attribute is defined. This example also demonstrates combining the attribute
selector with the :hover pseudo class and the :after pseudo element to display the href in
parentheses when the link is hovered over. Notice the use of the attr( ) function to retrieve the
value of an attribute.
a[href]:hover:after {
content: " (" attr(href) ")";
background-color: yellow;
}

Consider the following HTML document that has is three <a> elements, two of which
define the href attribute.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="default.css" rel="stylesheet" />
</head>
<body>
<a href='http://contoso.com' >Link 1</a><br />
<a>Link 2</a><br />
Free download pdf