skip to Main Content

I would like to change the appearance of the content in the <main> tag of my HTML page when an input box in the header nav is checked. This problem applies to a project I am working on but here is a simplified version showing the structure of my code:

nav input:checked+main {
  background-color: red;
}
<header>
  <nav>
    <input type="checkbox">
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
    </ul>
  </nav>
</header>
<main>
  Main page content
</main>

Ideally I would like to target the <footer> that succeeds the <main> tag as well. I have tried various selector combinations but the style of the main content does not change. Please note that ideally I do not want to change the structure of the page.

2

Answers


  1. You can’t do nav input:checked+main because main isn’t a sibling of the input (which is what the adjacent sibling combinator + checks for). You can try the newish :has pseudo-class instead:

    header:has(nav input:checked) + main {
      background-color: red;
    }
    <header>
      <nav>
        <input type="checkbox">
        <ul>
          <li>Item 1</li>
          <li>Item 2</li>
        </ul>
      </nav>
    </header>
    <main>
      Main page content
    </main>

    The way this works is basically targeting header + main only if the condition is the :has(nav input:checked) part is true.

    Login or Signup to reply.
  2. Adding to the accepted answer.
    for older browser support you need to move your input element outside the header element and then you can write below css for make this possible.
    Browser support for has here

    <!DOCTYPE html>
    <html>
    <head>
        <title>Test</title>
        <style>
        input[type="checkbox"]:checked~main  {
            background-color: red;
            border: 1px solid red;
        }
        </style>
        
    </head>
    <body>
      <input type="checkbox">
      <header>
        <nav>
          <ul>
            <li>Item 1</li>
            <li>Item 2</li>
          </ul>
        </nav>
      </header>
        <main>
            Main page content
        </main>
    </body>
    </html>
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search