: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
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.The selector
:not(p)
will select all elements that are notp
elements: This includeshtml
andbody
. We are settingcolor
on both these elements.Additionally, the property
color
is inherited by default.With
color
being inherited by default and us settingcolor
onbody
to red, thep
elements will inherit the value red forcolor
from their parent, namelybody
.You could select only children of
body
, meaning the de facto browser-default black forbody
‘scolor
will be inherited by thep
elements, while all other children that are notp
elements will havecolor
set to red.Note: With selector
body :not(p)
, only children ofbody
will havecolor
evaluate to black. Other elements will havecolor
set to red, which indirectp
descendants ofbody
will inherit.