Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS checkbox hack with non-sibling content

The following CSS checkbox hack works under the assumption that the content is a sibling of the checkbox. When the label is clicked, the content is toggled.

DEMO

<input id="checkbox" type="checkbox" />
<label for="checkbox">
  Toggle content
</label>
<div class="content">Content here</div>
#checkbox {
  display: none;
}

#checkbox:not(:checked) ~ .content {
  display: none;
}

Can the same effect be achieved using CSS only if the content is not a sibling of the checkbox? For example:

<div>
  <input id="checkbox" type="checkbox" />
  <label for="checkbox">
    Toggle content
  </label>
</div>
<div class="content">Content here</div>
like image 425
Misha Moroshko Avatar asked Jun 14 '26 16:06

Misha Moroshko


1 Answers

You could do it with the :target pseudo class and using anchors instead of a checkbox. Ugly as hell but CSS only:

a {
  color: #000000;
  text-decoration: none;
}

#off {
  display: none;
}

.content {
  display: none;
}

#your-target:target ~ .content {
  display: block;
}

#your-target:target #on {
  display: none;
}

#your-target:target #off {
  display: block;
}
<div id="your-target">
  <a id="on" href="#your-target">
    Toggle content
  </a>
  <a id="off" href="#">
    Toggle content
  </a>
</div>
<div class="content">Content here</div>
like image 113
r4ph43l Avatar answered Jun 16 '26 06:06

r4ph43l



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!