【问题标题】:Using CSS :not selector in LESS nested rules在 LESS 嵌套规则中使用 CSS :not 选择器
【发布时间】:2013-11-24 20:29:37
【问题描述】:
.outerclass {
    h3 {
        color: blue;
    }
    p:not(.nested) {
        color: green;
    }
}

在上面的 LESS 示例中,我希望定位 div 类“outerclass”中的所有“p”元素,但不定位称为“.nested”的进一步嵌套 div 中的 p 元素 - 它不起作用,而是使所有 p 元素绿色。我试过了……

p:not(.nested p) // excludes all p elements 

还有……

p:not(.nested > p) // excludes all p elements 

...无济于事。这是可能的还是我错过了什么?我是 LESS 的新手

【问题讨论】:

    标签: css css-selectors less


    【解决方案1】:

    这不像您的 css 选择器语法那样是一个 LESS 问题。 p:not(.nested) 是说所有没有.nested它们自己p 元素,你说的是.nested 类在div 上,p 驻留在其中,所以你需要这个:

    .outerclass {
        h3 {
            color: blue;
        }
        :not(.nested) p,
        > p {
            color: green;
        }
    }
    

    更新:我删除了 div 并添加了直接子 p 实例,以便 CSS 输出可以正确定位 .outerclass 中的所有 p,但例外情况除外。

    p 元素的 CSS 输出将是

    .outerclass :not(.nested) p,
    .outerclass > p {
      color: green;
    }
    

    以上将针对.outerclass 中的任何直接子p 元素和任何嵌套p 元素,除了那些是.nested 元素的子元素。

    一个问题

    BoltClock 注意到的问题是,p 的嵌套深度是否比 .nested 元素的直接子元素更深。 See this fiddle where the last p element is still targeted even though it is within a .nested class.

    如果p 元素始终是.nested 的直接子元素,则没有问题。或者如果.nested 始终是.outerclass 的直接子代,但p 可能嵌套更深,则可以将上述选择器更改为> :not(.nested) p 以生成.outerclass > :not(.nested) p 的CSS,其中will then work for all p under .nested

    问题将是如果.nested.outerclass.nested 中的p 相关对于这些父母来说都是任意深度。没有 css 选择器可以充分处理这个问题。

    【讨论】:

    • 请注意,:not(.nested) p 不等同于假设的:not(.nested p)。相反,它表示任何具有:not(.nested) 祖先的p。尽管您的选择器使用div 对其进行了限定,但它仍然是一个非常脆弱的选择器。
    • @BoltClock:由于这是 LESS 代码,因此我的示例中的最终输出选择器将是 .outerclass div:not(.nested) p,这似乎与 OP 根据对“target all 'p”的解释所寻求的匹配' div 类 'outerclass' 中的元素,但不是称为 '.nested' 的进一步嵌套 div 中的 p 元素”。
    • 感谢您的回答 ScottS,但它仍然不适用于我 - 未选择所有 p 元素。不过,我认为 BoltClock 的回答为我提供了一些启示——我从中了解到,使用这种格式实际上是不可能的。
    • @ScottS:这在很大程度上取决于 HTML 结构。如果没有任何其他div 元素将.outerclassp 元素分开,那么这样的选择器可能会起作用(尽管最好使用子选择器而不是后代选择器)。否则,使用带有:not() 的后代选择器通常会产生不必要的副作用。
    • @user2317093:我已经更新,因为我的答案最初不会针对所有p,但现在应该是。
    猜你喜欢
    • 1970-01-01
    • 2014-09-11
    • 2015-05-13
    • 2013-05-14
    • 1970-01-01
    • 2012-07-29
    • 2022-06-11
    • 2013-04-11
    相关资源
    最近更新 更多