【问题标题】:difference in css selectors? [duplicate]css选择器的区别? [复制]
【发布时间】:2016-08-23 03:27:35
【问题描述】:

这两个 css 选择器之间有什么区别,因为它们都给我相同的效果,然后使用 '>' 产生不同

  1. .abc > p
  2. .xyz p

.abc > p {
    background-color: yellow;
}

.xyz p {
    background-color: red;
}
<h1>Welcome to My Homepage</h1>

<div class="abc">
    <p>I live in Duckburg.</p>
    <h2>My name is Donald</h2>
    <p>I live in Duckburg.</p>
    <p>I live in Duckburg.</p>
    <p>I live in Duckburg.</p>
</div>

<p>My best friend is Mickey.</p>

<p>I will not be styled.</p>

<div class="xyz">
    <p>I live in Duckburg.</p>
    <h2>My name is Donald</h2>
    <p>I live in Duckburg.</p>
    <p>I live in Duckburg.</p>
    <p>I live in Duckburg.</p>
</div>

【问题讨论】:

  • 但基本上 - .abc &gt; p 将仅选择其直接父级为 .abcp 标签,而 xyz p 将选择 p 内的任何 p 元素@ (@987654321 @)
  • 感谢大家的帮助

标签: css


【解决方案1】:

div

Selects all <p> elements inside <div> elements  

div > p

Selects all <p> elements where the parent is a <div> 

【讨论】:

    【解决方案2】:

    使用.abc &gt; p {} 将适用于作为.abc 的直接后代的所有p 元素:

    <div class="abc">
        <p>I'm affected</p>
        <div class="test">
            <p>I'm not</p>
        </div>
    </div>
    

    使用.xyz p {} 适用于.xyz 中的所有p 元素,无论它们是直系后代、孙辈、曾曾孙辈等:

    <div class="xyz">
        <p>I'm affected</p>
        <div class="test">
            <p>I'm affected</p>
            <div class="anothertest">
                <p>I'm also affected</p>
            </div>
        </div>
    </div>
    

    【讨论】:

    • 我认为受影响的应该受到影响。但实际的解决方案是正确的
    • @AdamHughes 刚刚更正了拼写 - 为指出而欢呼。
    【解决方案3】:

    &gt; 符号针对特定部分的任何直接子级,在您的情况下为 .abc。没有它,该样式也适用于该类的任何子子项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      • 2018-12-17
      相关资源
      最近更新 更多