Search code examples
htmlcsscss-selectorspseudo-class

Use 'not' pseduo-class to style all the elements except the one that is a child of a specific one


h1 { color: red; }
header h1 { color: revert; }
<body>
  <header>
    <h1>Title</h1>
  </header>
  <h1>Level-1 heading</h1>
  <p>Body text.</p>
  <h1>Level-1 heading</h1>
  <p>Body text.</p>
</body>

I want to make <h1> elements red, except the <h1> inside <header>. I can do it using,

h1 { color: red; }
header h1 { color: revert; }

but maybe there is a better way, using a single declaration and without overwriting?

I tried :not(header) h1 { color: red; }, but for some reason it doesn't work. Another approach is body > h1 { color: red; }, but it is somewhat fragile for me.


Solution

  • I want to make <h1> elements red, except the <h1> inside <header>.

    h1:not(header h1) {
      color:red
    }
    

    h1:not(header h1) {
      color: red
    }
    <header>
      <h1>Title</h1>
    </header>
    <h1>Level-1 heading</h1>
    <p>Body text.</p>
    <h1>Level-1 heading</h1>
    <p>Body text.</p>