UX Design and Development course

Decedent, Child and Sibling selectors

Decedent selectors

The combinator (that's meant to represent a space, or more properly one or more whitespace characters) combines two selectors such that the combined selector matches only those elements matching the second selector for which there is an ancestor element matching the first selector. Descendant selectors are similar to child selectors, but they do not require that the relationship between matched elements be strictly parent-child.

Syntax

selector1 selector2 { style properties }

Example

<div>
  <span>Span 1.
    <span>Span 2.</span>
  </span>
</div>
<span>Span 3.</span>
span { background-color: white; }
div span { background-color: DodgerBlue; }

Child selectors

The > combinator separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first. By contrast, when two selectors are combined with the descendant selector, the combined selector expression matches those elements matched by the second selector for which there exists an ancestor element matched by the first selector, regardless of the number of "hops" up the DOM.

Syntax

selector1 > selector2 { style properties }

Example

<div>
  <span>Span 1. In the div.
    <span>Span 2. In the span that's in the div.</span>
  </span>
</div>
<span>Span 3. Not in a div at all</span>
span { background-color: white; }
div > span {
  background-color: DodgerBlue;
}

Adjacent sibling selectors

This is referred to as an adjacent selector. It will select only the specified element that immediately follows the former specified element.

Syntax

former_element + target_element { style properties }

Example

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>
li:first-of-type + li {
  color: red;
}

General sibling selectors

The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.

Syntax

element ~ element { style properties }

Example

<span>This is not red.</span>
<p>Here is a paragraph.</p>
<code>Here is some code.</code>
<span>And here is a span.</span>
p ~ span {
  color: red;
}