Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

152 CHAPTER 4 Getting started with CSS3


background to yellow. The second <div> element is followed by some textual content, but
the first element that follows the second <div> element is an <h1> element, so that <h1>
element will have a yellow background. The result is shown in Figure 4-1.

FIGURE 4-1 Only one <h1> element background color set to yellow

Using the subsequent sibling selector
The subsequent sibling selector is similar to the adjacent sibling selector, but its search for the
sibling match doesn’t stop at the first match. The tilde (~) character denotes the sibling selec-
tor. For example, div ~ h1 selects all <h1> elements that follow a <div> element.
In the following example, div ~ h1 sets the heading to a background color of yellow if the
heading is preceded by a <div> element as a previous sibling.
div ~ h1 {
background-color: yellow;
}

Using the HTML document from the adjacent sibling selector example, 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, but sibling <h1> ele-
ments follow, and their backgrounds are changed to yellow. The second <div> element is
followed by some textual content, and two <h1> elements follow the second <div> element;
they will have a yellow background. Notice that with both <div> elements, there is an <h1>
element before the <div> element, and their background color is not set to yellow because
although they are siblings, they are prior siblings. The result is shown in Figure 4-2.
Free download pdf