Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

nesting inside css :not() selectors

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.

Depending on which elements you're trying to select exactly, there may not be a way to exclude 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)
    
  • 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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...