Reputation: 85
I have a checkbox which hides/shows a div. It works when I put the checkbox directly above the div. When I place the checkbox somewhere else in the page (for better usability) it doesnt't work. Is there a way to target a certain div to make the checkbox work from everywhere on the page?
Here is the HTML-code:
<input type="checkbox" id="toggle-result" checked="checked"> </input>
CSS:
input[type=checkbox]:checked ~ div {
display: none;
}
Upvotes: 0
Views: 3870
Reputation: 157374
Using CSS, you can select child elements and adjacent elements, so what you are trying to do will work if div
is placed right after the checkbox but if you want to make it work when div
is somewhere else(above the checkbox), you need to use JavaScript, if it's after, you can use +
to select adjacent element or nested adjacent element
<input type="checkbox" />
<div>Toggle Using CSS</div>
input[type=checkbox]:checked + div {
display: block;
}
div {
display: none;
}
Targetting div
which is farther away somewhere (But not before the checkbox
) like this
input[type=checkbox]:checked + a + .blah .target {
display: block;
}
.target {
display: none;
}
<input type="checkbox" />
<a href="#">Dummy Link</a>
<div class="blah">
<div class="target">Complicated Selector, Isn't It?</div>
</div>
Explanation :
input[type=checkbox]:checked + a + .blah .target
Over here we select the checkbox which is in a checked state, and than we chain this by selecting the adjacent element which is an anchor tag, and than we select another adjacent element which is adjacent toa
tag which isdiv
with a class.blah
, and than we select nested child element with a class.target
Using jQuery To Do (Doesn't matter where the target element is) Demo 3
<input type="checkbox" id="checkme" />
<a href="#">Dummy Link</a>
<div id="show_on_check" style="display:none">
This content should appear when the checkbox is checked
</div>
$(document).ready(function() {
$('#checkme').change(function() {
$('#show_on_check').toggle();
});
});
Upvotes: 6
Reputation: 22001
Use the element IDs in your selectors:
<input type="checkbox" id="toggle-result" checked="checked"/>
<div id="myDiv">showme</div>
<style>
#toggle-result:checked ~ #myDiv {
display: none;
}
</style>
Upvotes: 0
Reputation: 70748
input[type=checkbox]:checked ~ div {
display: none;
}
Will select every div
element that is preceded by a input
that is checked. The reason why it probably breaks is because the input is not preceding the div
(Like you state in your question)
Upvotes: 0