Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1
Lesson 2: Understanding selectors, specificity, and cascading CHAPTER 4 151

color: gray;
}

Using subsequent adjacent sibling selectors
An adjacent selector can be used to select an element if it is preceded by a specific element.
The plus (+) sign denotes an adjacent selector. For example, div + h1 selects the <h1> ele-
ment that immediately follows a <div> element.
In the following example, div + h1 set the heading to a background color of yellow if the
heading is preceded by a <div> element as the previous sibling.
div + h1 {
background-color: yellow;
}

Consider the following HTML document, which has two <div> elements and various <h1>
elements.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="default.css" rel="stylesheet" />
</head>
<body>
<h1>The h1 child before the first div
</h1>
<div>
some child content
<h1>This is the first h1 child
</h1>
<div>another div here</div>
some text after the div
<h1>This is the second h1 child
</h1>
<h1>This is the third h1 child
</h1>
</div>
some following content
<span>here is a span</span>
<h1>This the first h1 that follows the paragraph
</h1>
<h1>This the second h1 that follows the paragraph
</h1>
<h1>This the third h1 that follows the paragraph
</h1>
</body>
</html>
The first <div> element has child <h1> elements, but they are children, not adjacent
elements. The adjacent element that follows the first <div> element is the <span> element,
which means that the first <div> element does not play a role in changing an <h1> element’s

Key
Te rms

Free download pdf