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
232 views
in Technique[技术] by (71.8m points)

html - CSS :not pseudo-class not working

I am learning about the :not() pseudo class and it is not working as expected.

I want to color all text red except for .mind. For some reason this is not preventing the .mind element from being red.

:not(.mind) {
  color: red
}
<div class='parent'>
  <div class='child'>One</div>
  <div class='child'>Two</div>
  <div class='child'>Three</div>
  <div class='child'>One</div>
  <div class='child'>Two</div>
  <div class='child'>Three</div>
  <div class='child'>One</div>
  <div class='mind'>mind</div>
  <div class='child'>Three</div>
  <div class='child'>
    <p>First paragraph</p>
  </div>
</div>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Keep this in mind:

:not() is equivalent to *:not()

When there is no selector prefixing the :not() pseudo-class, a universal selector is implied:

6.2. Universal selector

If a universal selector represented by * (i.e. without a namespace prefix) is not the only component of a sequence of simple selectors selectors or is immediately followed by a pseudo-element, then the * may be omitted and the universal selector's presence implied.

Therefore, the rule you have:

:not(.mind) {
  color: red
}

... is saying apply red color to all elements except the element with the class mind.

Okay, except in this case, the color property is inheritable, so even though the red doesn't get applied to the .mind element, it still gets the red through inheritance from the .parent element.

Here's what the browser is doing:

enter image description here

A quick way to test this behavior is with the border property, which is not inheritable.

In the example below, using your selector, you'll notice that the border doesn't get applied to .mind, and your selector works as you were expecting:

:not(.mind) {
  color: red;
  border-bottom: 1px dashed black;
}
<div class='parent'>
  <div class='child'>One</div>
  <div class='child'>Two</div>
  <div class='child'>Three</div>
  <div class='child'>One</div>
  <div class='child'>Two</div>
  <div class='child'>Three</div>
  <div class='child'>One</div>
  <div class='mind'>mind</div>
  <div class='child'>Three</div>
  <div class='child'>
    <p>First paragraph</p>
  </div>
</div>

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

...