CSS '>' selector; what is it?

Possible Duplicate:
What does “>” mean in CSS rules?

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?


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

> selects all direct descendants/children

A space selector will select all deep descendants whereas a greater than > selector will only select all immediate descendants. See fiddle for example.

div { border: 1px solid black; margin-bottom: 10px; }
.a b { color: red; } /* every John is red */
.b > b { color: blue; } /* Only John 3 and John 4 are blue */
<div class="a">
  <p><b>John 1</b></p>
  <p><b>John 2</b></p>
  <b>John 3</b>
  <b>John 4</b>
</div>

<div class="b">
  <p><b>John 1</b></p>
  <p><b>John 2</b></p>
  <b>John 3</b>
  <b>John 4</b>
</div>

It is the CSS child selector. Example:

div > p selects all paragraphs that are direct children of div.

See this

链接地址: http://www.djcxy.com/p/3908.html

上一篇: 领域和财产之间有什么区别?

下一篇: CSS'>'选择器; 它是什么?