CSS '>' selector; what is it?

Bojangles picture Bojangles · Dec 16, 2010 · Viewed 326.6k times · Source

I've seen the "greater than" (>) used in CSS code a few times, but I can't work out what it does. What does it do?

Answer

Spudley picture Spudley · Dec 16, 2010

> selects immediate children

For example, if you have nested divs like such:

<div class='outer'>
    <div class="middle">
        <div class="inner">...</div>
    </div>
    <div class="middle">
        <div class="inner">...</div>
    </div>
</div>

and you declare a css rule in your stylesheet like such:

.outer > div {
    ...
}

your rules will apply only to those divs that have a class of "middle" since those divs are direct descendants (immediate children) of elements with class "outer" (unless, of course, you declare other, more specific rules overriding these rules). See fiddle.

div {
  border: 1px solid black;
  padding: 10px;
}
.outer > div {
  border: 1px solid orange;
}
<div class='outer'>
  div.outer - This is the parent.
  <div class="middle">
    div.middle - This is an immediate child of "outer". This will receive the orange border.
    <div class="inner">div.inner - This is an immediate child of "middle". This will not receive the orange border.</div>
  </div>
  <div class="middle">
    div.middle - This is an immediate child of "outer". This will receive the orange border.
    <div class="inner">div.inner - This is an immediate child of "middle". This will not receive the orange border.</div>
  </div>
</div>

<p>Without Words</p>

<div class='outer'>
  <div class="middle">
    <div class="inner">...</div>
  </div>
  <div class="middle">
    <div class="inner">...</div>
  </div>
</div>

Side note

If you, instead, had a space between selectors instead of >, your rules would apply to both of the nested divs. The space is much more commonly used and defines a "descendant selector", which means it looks for any matching element down the tree rather than just immediate children as the > does.

NOTE: The > selector is not supported by IE6. It does work in all other current browsers though, including IE7 and IE8.

If you're looking into less-well-used CSS selectors, you may also want to look at +, ~, and [attr] selectors, all of which can be very useful.

This page has a full list of all available selectors, along with details of their support in various browsers (its mainly IE that has problems), and good examples of their usage.