【问题标题】:CSS :not selector does not neglect the next selectorCSS :not 选择器不会忽略下一个选择器
【发布时间】:2021-08-06 11:08:00
【问题描述】:

<p> 上方的标签不属于某个类时,我有一个样式可以应用,例如:

:not(.someclass) + p {
    color: yellow
}

这适用于以下情况:

<h3 class="someclass">title</h3>
<p>This does not have the style applied</p>
<p>This has the style applied</p>

困扰我的是当&lt;p&gt;上方没有标签时,我希望应用该样式但它没有,例如:

<p>This should have the style applied but it doesn't</p>

您将如何修复 CSS 以涵盖这两种情况?

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    只有当段落没有先前的兄弟姐妹时,您的选择器才会失败,这意味着它必须是第一个孩子,因此修改您的规则如下:

    :not(.someclass) + p,
    p:first-child {
        color: yellow
    }
    

    :not(.someclass) + p,
    p:first-child {
        color: yellow
    }
    <div>
      <h3 class="someclass">title</h3>
      <p>This does not have the style applied</p>
      <p>This has the style applied</p>
    </div>
    
    <div>
      <p>This should have the style applied but it doesn't</p>
    </div>

    【讨论】:

    • 这太棒了!正在考虑 :not() 选择器是否会以某种方式影响 + 选择器,但看起来我需要这两部分 CSS 来解决它。
    • 你需要从右边读取选择器:你的目标是一个段落,该段落必须是非 .someclass 的下一个兄弟
    • 是的,我知道,但我读的就像&lt;p&gt;,后面没有类 someclass 的东西
    猜你喜欢
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多