Close div when checkbox clicked with pure css

I am trying to close a div when I click on a checkmark using css, but not JQuery or Javascript, but it seems like it is 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>
Run codeHide result

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

+4
source share
4 answers

I think the only way to do this with pure css is to set the checkbox as the direct sibling in 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>
Run codeHide result
+1
source

#text{
  width:100px;
  height:100px;
  background:black;
}
input[type=checkbox]:checked ~ #text{
display:none;
 
}
<input type="checkbox" name="check" value="checked">Click here<br>
<div id="text"></div>
Run codeHide result
+1
source

CSS, - .

JSFiddle

+ - , https://developer.mozilla.org/en/docs/Web/CSS/Adjacent_sibling_selectors

#close + #div-1 {
    display: none;
}

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

, , , html.

<input type="checkbox" checked>
<div id="div-1">          
     Here is the content. 
</div

css

div[id^="div-"] {
    display: block;
}


input:checked ~ div[id^="div-"] {
    display: none;
}

jsfiddle

+1
source

Source: https://habr.com/ru/post/1653420/


All Articles