Child selectors

  • Revision slug: CSS/Child_selectors
  • Revision title: Child selectors
  • Revision id: 9125
  • Created:
  • Creator: Pointy
  • Is current revision? No
  • Comment 71 words added, 15 words removed

Revision Content

{{ CSSRef() }}

Summary

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

Syntax

selector1 > selector2 { style properties }

Examples

span { background-color: white; }
div > span {
  background-color: DodgerBlue;
}

when applied to markup as follows:

<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>

should result in:

Span 1. In the div. Span 2. In the span that's in the div.
Span 3. Not in a div at all.

Notes

{{ languages( { "fr": "fr/CSS/:first-child", "pl": "pl/CSS/:first-child" } ) }}

Revision Source

<p>{{ CSSRef() }}</p>
<h3 name="Summary">Summary</h3>
<p>The <code>&gt;</code> combinator separates two selectors and matches only those elements selected by the second selector that are <strong>direct</strong> children of elements matching the first. By contrast, when two selectors are combined with the <a href="/en/CSS/Descendant_selectors" title="https://developer.mozilla.org/en/CSS/Descendant_selectors">descendant selector</a>, then the combined selector expression matches elements selected by the second selector for which there exists an ancestor element matching the first selector, regardless of the number of "hops" up the DOM.</p>
<h3 name="Syntax">Syntax</h3>
<pre class="eval">selector1 &gt; selector2 { <em>style properties</em> }
</pre>
<h3 name="Examples">Examples</h3>
<pre class="brush: css">span { background-color: white; }
div &gt; span {
  background-color: DodgerBlue;
}
</pre>
<p>when applied to markup as follows:</p>
<pre class="brush: html">&lt;div&gt;
  &lt;span&gt;Span 1. In the div.
    &lt;span&gt;Span 2. In the span that's in the div.&lt;/span&gt;
  &lt;/span&gt;
&lt;/div&gt;
&lt;span&gt;Span 3. Not in a div at all&lt;/span&gt;
</pre>
<p>should result in:</p>
<p style="margin-left: 40px;"><span style="background-color: DodgerBlue;">Span 1. In the div.</span> <span>Span 2. In the span that's in the div.</span><br>
<span>Span 3. Not in a div at all.</span></p>
<p>Notes</p>
<p>{{ languages( { "fr": "fr/CSS/:first-child", "pl": "pl/CSS/:first-child" } ) }}</p>
Revert to this revision