【问题标题】:What are the differences between > and space? [duplicate]> 和空格之间有什么区别? [复制]
【发布时间】:2017-08-22 11:34:47
【问题描述】:

这两种风格有什么区别:

element1 > element2 {
   ...
}

element1 element2 {
   ...
}

【问题讨论】:

  • > - 是直系子
  • 空格选择所有后代,而> 只选择孩子

标签: css


【解决方案1】:

element1 element2 选择element1 内的所有元素

示例

<style>
.element1 .element2{ 
    color: #2196F3;
    background-color: #FFEB3B;
}
</style>

<div class="element1">
    <p class="element2">
        As you can see that this paragraph with class `element2` is inside div with class `element1` and so it's catched by css written above.
    </p>
</div>

element1 &gt; element2 选择父级为element1 的每个element2

<style>
.element1 > .element2{ 
    color: #2196F3;
    background-color: #FFEB3B;
}
</style>

<div class="element1">
    <p class="element2">
        This paragraph is catched by css above because this paragraph with class `element2` is immediate child of div with class `element1`.
    </p>
</div>

<!--no effect-->
<div class="element1">
   <div class="middleelement">
      <p class="element2">
          This paragraph is <strong>NOT</strong> catched by css written above because it's not immediate child of div with class `element1` because class `middleelement` comes in between. To refer to this paragraph, you have to write css as `.element1 &gt; .middleelement &gt; .element2`
      </p>
   </div>
</div>

【讨论】:

    【解决方案2】:

    element1 &gt; element2 选择所有&lt;element2&gt; 元素,其中父元素是&lt;element1&gt; 元素(请参阅child combinator selector 了解更多信息),而element1 element2 选择&lt;element1&gt; 元素内的所有&lt;element2&gt; 元素(请参阅descendant selector了解更多信息)。

    示例:
    如果您必须遵循 DOM 标记(请参阅此 JSFiddle):

    a
      c
      b
        c
      d
        c
    

    如果你使用a c {bg -&gt; red}(伪代码),所有c 元素都会变成红色,但如果你也使用a &gt; c {bg -&gt; blue},第一个c 元素会变成蓝色,而另一个会变成红色。这是因为 a 元素是第一个 c 元素的直接父元素。

    【讨论】:

      【解决方案3】:

      &gt;child combinator,表示直接子元素,而空格(或&gt;&gt;)是descendant combinator,意味着另一个元素可以在第一个元素内的任何位置。

      如果你有以下 DOM 树

      a
        b
          c
        d
      

      那么a &gt; c 将不匹配任何内容,而a c 将匹配c 元素。

      【讨论】:

        【解决方案4】:
        element1 element2
        

        选择elements内的所有elements

        element1 > element2
        

        选择父级为element的所有elements

        【讨论】:

          猜你喜欢
          • 2016-09-05
          • 1970-01-01
          • 2013-06-10
          • 2011-10-31
          • 2017-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-20
          相关资源
          最近更新 更多