Want to share your CSS expertise with others? Apply to the MDN Fellowship by April 1! http://mzl.la/MDNFellowship

mozilla

Revision 9126 of Child selectors

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

Revision Content

{{ CSSRef() }}

Summary

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 }

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 matched by the second selector that are <strong>direct</strong> children of elements matched by 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>, 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.</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