Search code examples
htmlcsscheckboxshow-hide

close a div when a checkbox clicked with pure css


I am trying to close a div when a checkbox is clicked with css only not JQuery or Javascript but it seems not working properly. How can I adjust it?

    div[id^="div-"] {
     	display: block;
    }
    div[id^="div-"]:target {
	    display: none;
    }
    <a href="#div-1"><input type="checkbox" checked></a>
    <div id="div-1">          
         Here is the content. 
    </div>

How can I link the <a> click and the checkbox?


Solution

  • I think the only way to do this with pure css would be to have the checkbox as a direct sibling to the div:

    #div-1 {display:none}
    #checkbox:checked + #div-1 {display:block;}
    <input id="checkbox" type="checkbox" checked>
    <div id="div-1">          
         Here is the content. 
    </div>