.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选择器语法那么少。 p:not(.nested)表示所有没有p类的.nested元素本身,您声明的是.nested类位于div所在的p上,因此您需要这样做:

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

更新:我删除了div并添加了直接子p实例,以便CSS输出将正确地针对p中的所有.outerclass(异常(exception)除外)。

元素的CSS输出为
.outerclass :not(.nested) p,
.outerclass > p {
  color: green;
}

上面的代码将定位到p中的所有直接子p元素和任何嵌套p元素,但那些是.outerclass元素的子元素的除外。

问题

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

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

问题将在于,相对于.nested.nested.outerclass中的p都对那些父级而言处于任意深度。没有CSS选择器可以适当地处理该问题。

关于css - 在较少的嵌套规则中使用CSS:not选择器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19933445/

10-13 01:07