skip to Main Content

I want to toggle a <div> via a checkbox.


<div class="docs">...</div>

...

<input type="checkbox" id="toggle-docs">

The docs should only be visible if the checkbox is checked.

This should work without JS.

Up to now I only found solutions which require the checkbox to be near the div (via + or ~ selector).

Is there a way to solve this with modern CSS?

2

Answers


  1. Chosen as BEST ANSWER

    This is doable with :has which has baseline support since December 2023.

    div.docs {
        display: none;
    }
    
    body:has(#toggle-docs:checked) div.docs  {
        display: block;
    }
    

    This shows docs only, if the checkbox is checked.


  2. using the adjacent sibling combinator (+) in CSS, even if the checkbox is not directly adjacent to the <div> you want to toggle. You can achieve this by using the :checked pseudo-class along with the adjacent sibling combinator.

    #toggle-docs:checked + .docs {
      display: block;
    }
    
    .docs {
      display: none;
    }
    <input type="checkbox" id="toggle-docs">
    <div class="docs">...</div>
    <label for="toggle-docs">Toggle Docs</label>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search