0

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • Does this answer your question? [Is there a CSS parent selector?](https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – InSync May 09 '23 at 17:08
  • You can place that checkbox outside of `
    ` and use a pseudo-checkbox made of `
    – InSync May 09 '23 at 17:11
  • That is actually exactly what I am doing! My code snippet was just the simplest way to demonstrate my issue. Appreciative of the quick responses. – Matthew Bishop May 09 '23 at 17:16

2 Answers2

2

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
0

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>

Incoglee
  • 26
  • 3
  • Thank you for the extra information. I found out `:has` support for Firefox should be coming [soon](https://connect.mozilla.org/t5/discussions/when-is-has-css-selector-going-to-be-fully-implemented-in/m-p/27010/highlight/true#M10711). – Matthew Bishop May 10 '23 at 09:17