skip to Main Content
:not(p) {
  color: #ff0000;
}
<h1>This is a heading</h1>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<div>This is some text in a div element.</div>

<a href="https://www.w3schools.com" target="_blank">Link to W3Schools!</a>

The not(selector) is used to select every element that is not specified element, So in the above code i am getting red color on both p which is a non-selected item.

I am expecting only div,a,h1 to be red, not p as p is a specified element and it is meant to be leave and style have to apply to all others element?

2

Answers


  1. The :not selector doesn’t work like that. Before the :not selector you should tell from which parent do you want to select.

    body :not(p) targets all elements that are not paragraph elements within the of the HTML document and applies a red color (#ff0000) to their text.

    body :not(p) {
        color: #ff0000;
    }
    <body>
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <div>This is some text in a div element.</div>
    <a href="https://www.w3schools.com" target="_blank">Link to W3Schools!</a>
    </body>
    Login or Signup to reply.
  2. The selector :not(p) will select all elements that are not p elements: This includes html and body. We are setting color on both these elements.

    Additionally, the property color is inherited by default.

    With color being inherited by default and us setting color on body to red, the p elements will inherit the value red for color from their parent, namely body.


    You could select only children of body, meaning the de facto browser-default black for body‘s color will be inherited by the p elements, while all other children that are not p elements will have color set to red.

    Note: With selector body :not(p), only children of body will have color evaluate to black. Other elements will have color set to red, which indirect p descendants of body will inherit.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search