skip to Main Content
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.

2

Answers


  1. 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>
    Login or Signup to reply.
  2. body:not(header) > h1 {
    color: red;
    }
    <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>
    body:not(header) > h1 {
        color: red;
    }
    

    This will make all <h1> elements red except for those inside a <header>.

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