Select elements based on their relationships in the document.
Sometimes a class or element name is not enough. You may want paragraphs inside a particular section, or the paragraph immediately after a heading.
A combinator connects selectors by describing a relationship between elements in the HTML structure.
Use the same HTML for all four relationships. Start with the descendant selector in the stylesheet tab.
.article p {
color: green;
}The structure gives us three useful terms:
div are siblings.When a selector has two parts, start with the element on the right. That is the
element the rule can style. Then use the combinator and the selector on the left
to check its relationship. For example, in .article > p, begin with each p,
then keep only the ones whose direct parent is .article.
A space between selectors matches descendants at any depth.
All three paragraphs inside .article match, including the paragraph inside the div. The paragraph outside the section does not match. The section itself is not selected by this rule.
>Use > when the target must be directly inside the first element:
.article > p {
color: green;
}This matches “Read the introduction” and “Check the summary.” The nested paragraph does not match because its parent is the div, not the section.
Compare the reach:
.article p: Paragraphs at any depth inside the section..article > p: Only paragraphs whose direct parent has the class article.+Use + to select a matching element immediately after another element with the same parent:
h2 + p {
color: green;
}Only “Read the introduction” matches: it is the next element after the heading. Spaces and line breaks between HTML tags do not affect the match.
The + combinator is also called the adjacent-sibling combinator.
~Use ~ to match later siblings, even when other elements are between them:
h2 ~ p {
color: green;
}Both outer paragraphs match. The nested paragraph does not share the heading's parent, so it does not match. This is the subsequent-sibling, or general-sibling, combinator.
Use the relationships in the article to complete the target selector before checking the result:
/* Select the paragraph immediately after the heading. */
h2 + ____ {
color: green;
}The blank is p: start with the target element, then check that it is the next
sibling of h2. Once that relationship is clear, write the full selector
h2 + p without the prompt.
Try it yourself
HTML + CSS
>: Matches direct children only.+: Matches the next element sibling when it satisfies the second selector.~: Matches later siblings that satisfy the second selector.