![]() Selecting Elements by ContextIn CSS you can pinpoint elements depending on their ancestors, their parent, or their siblings (see page 31). An ancestor is any element that contains the desired element (the descendant), regardless of the number of generations that separate them. Figure 9.12. I've snipped the text to make the relationships between elements easier to see. Each indentation represents a generation. Note that there are two second generation p elements, directly within the gaudi div, and one third generation p element, within the works divs (within the gaudi div).
To select elements to format based on their ancestor:
Figure 9.14. All of the p elements that are contained within the gaudi div are red, even if they're also within other elements within that gaudi div.
A parent is the element that directly contains the desired element (the child) with no intermediate containing elements. To select elements to format based on their parent:
Figure 9.16. Only the first two p elements are children of the gaudi div. The two other p elements are children of the works div. For the (X)HTML code used in this example, see Figure 9.12 on page 141.
It's sometimes useful to be able to select only the first child of an element, as opposed to all of the children of an element. To select elements to format that are the first child of their parent:
An adjacent sibling is the element that directly precedes the desired element within the same parent element. Figure 9.19. The first p element contained in the gaudi div is red. The second one isn't.
To select elements to format based on an adjacent sibling:
Figure 9.20. This selector chooses only those p elements which directly follow a sibling p element.
![]() |