嵌套在 css :not() 选择器中

时间:2022-11-29
本文介绍了嵌套在 css :not() 选择器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 :not 选择器中包含嵌套值?例如:

Is it possible to have nested values inside the :not selector? For eg:

:not(div > div)

每当我尝试它时,它似乎都不起作用.也许您需要以另一种我还没有想到的方式使用它?到目前为止,在我看到的所有示例中,您只能在此选择器中使用一个值.

Whenever I tried it, it does not seem to work. Perhaps you need to use it another way which I have not figured out? So far, in all the examples I see, you can only use one value inside this selector.

推荐答案

:not() 一次只接受一个简单的选择器;Selectors 3 规范中提到了这一点:

:not() only accepts one simple selector at a time; this is mentioned in the Selectors 3 spec:

否定伪类 :not(X) 是一个采用 简单选择器(不包括否定伪类本身)作为参数.它表示其参数未表示的元素.

The negation pseudo-class, :not(X), is a functional notation taking a simple selector (excluding the negation pseudo-class itself) as an argument. It represents an element that is not represented by its argument.

您的示例中的简单选择器将是您拥有的两个 div 标记.其他简单的选择器包括类选择器、ID 选择器、属性选择器和伪类.它不接受多个简单的选择器,也不接受 > 或空格等组合符.

The simple selectors in your example would be the two div tokens that you have. Other simple selectors include class selectors, ID selectors, attribute selectors and pseudo-classes. It does not accept more than one simple selector, nor does it accept combinators like > or space.

根据您要准确选择的元素,可能无法排除 div >div:

Depending on which elements you're trying to select exactly, there may not be a way to exclude div > div:

  • 如果您只想选择 div 的子元素,而这些元素本身不是 div,请改用:

  • If you only want to select elements that are children of a div, that are themselves not div, use this instead:

div > :not(div)

  • 如果您只想选择父元素不是 divdiv 元素,请改用:

  • If you only want to select div elements whose parent element is not a div, use this instead:

    :not(div) > div
    

  • 如果你想单独使用这个否定,选择所有个其他元素,那么只使用一个选择器是没有办法的.

    If you want to use this negation by itself, selecting all other elements, then there isn't a way using just a selector.

    我能想到的唯一其他可行的 CSS 解决方法是在没有 :not() 表达式的情况下将样式应用于您想要的元素,然后为 div > 撤消它们.div.这适用于您尝试定位的任何一组元素;缺点是并非所有属性都可以轻松重置.

    The only other viable workaround in CSS that I can think of is to apply styles to the elements you want without the :not() expression, then undo them for div > div. This works for any set of elements you're trying to target; the disadvantage is that not all properties can be easily reset.

    或者,如果您使用 jQuery,它确实支持 :not(div > div) 与 CSS 版本不同,您可以将选择器放在脚本中,例如,让 jQuery 将类名应用于那些然后元素在您的 CSS 中定位该类.

    Alternatively, if you're using jQuery, which does support :not(div > div) unlike the CSS version, you can place the selector in a script and, for instance, have jQuery apply a class name to those elements then target that class in your CSS.

    这篇关于嵌套在 css :not() 选择器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

    上一篇:兄弟选择器 * + * 和 * ~ * 背后的逻辑是什么? 下一篇:哪种方法更好?CSS类或ID?

    相关文章

    最新文章