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
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:The way this works is basically targeting
header + main
only if the condition is the:has(nav input:checked)
part is true.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