简体   繁体   中英

HTML: Turn Element invisible when checkbox is checked

I have a checkbox in the header of my html code and a box in the body. I need the box to disappear when the checkbox is checked.

I will provide the code below but in short I can make the checkbox itself disappear when it is checked but when I add in the class of the element I want to vanish it stops working at all. I have tried a couple different forms of the CSS but nothing has changed it.

 #toggle:checked ~ div .sidebar{ display:none; } .sidebar { width: 100px; height: 100px; background: #000; } 
 <nav class="navbar"> <div class="container"> <div class="navbar-header"> <label for="toggle" class="sidebar-toggle"></label> </div> <input type="checkbox" id="toggle" /> </div> </nav> <div class="sidebar"> </div> 

You have a small typo in your CSS selector #toggle:checked ~ div .sidebar . There should be no space between div and .sidebar because your goal is to select "the div with class name sidebar " (not "any element with class name sidebar that is a child of a div ").

Another issue is that you are incorrectly using the Adjacent Sibling Combinator in your CSS selector. In order for your selector to work properly, the div.sidebar should be a child of the same parent as the #toggle element.

 #toggle:checked ~ div.sidebar { display: none; } .sidebar { width: 100px; height: 100px; background: #000; } 
 <nav class="navbar"> <div class="container"> <div class="navbar-header"> <label for="toggle" class="sidebar-toggle"></label> </div> <input type="checkbox" id="toggle" /> <div class="sidebar"></div> </div> </nav> 

Assuming you cannot change your HTML structure, since you are trying to alter a "div" that is not a sibling or a descendent of the checkbox, you will need javascript to do this.

 function handleChange(checkbox) { if (checkbox.checked == true) { document.getElementsByClassName("sidebar")[0].classList.add("hidden");; } else { document.getElementsByClassName("sidebar")[0].classList.remove("hidden");; } } 
 .sidebar.hidden { display: none; } .sidebar { width: 100px; height: 100px; background: #000; } 
 <nav class="navbar"> <div class="container"> <div class="navbar-header"> <label for="toggle" class="sidebar-toggle"></label> </div> <input type="checkbox" id="toggle" onchange='handleChange(this)' /> </div> </nav> <div class="sidebar"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM