I want to make "onclick" effect on mobile with checkbox:checked (without using JS)

72 views Asked by At

I want my dropup content to appear when I check my checkbox, but it isn't working. Dropup-content by default has visibility: collapse, so I want it to have visibility: visible when I check the checkbox. how it should look

I tried to put .dropup-content under input:checked + span but nothing change

index.html:

<label for="sports">  
  <input type="checkbox" id="sports" class="checkbox">  
  <span class="span-label">Sports</span>  
</label>  
<div class="dropup-content">  
  <a href="">More...</a>  
  <a href="">Esports</a>  
  <a href="">Handball</a>  
  <a href="">Basketball</a>  
  <a href="">Football</a>  
</div>

index.scss:

input:checked + span {
    color: orange;  //changes color of text Sports
   .dropup-content {
       visibility: visible;
       max-height: 250px; 
       transition: max-height 0.2s; 
  } 
}
2

There are 2 answers

0
lan-e On BEST ANSWER

I ended up using inputs rather than checkbox. But I wanted to post a solution. So, it had to do with subtree, but also in css you have to use ~ to refer to sibling element:

This solved my problem:

input:checked + label {  
  color: orange;
} 
input:checked ~ .dropup-content {
  visibility: visible;
  max-height: 250px;
  transition: max-height 0.2s;
}
1
Stephane Vanraes On

.dropup-content is not in the same subtree as the checkbox or the span, so you cannot reach it with a simple sibling selector.

What you can do however is use the new :has selector, (check https://caniuse.com/css-has for supported browser).

In that case the rule would become:

label:has(input:checked) + .dropup-content {
 visibility: visible;
}

If you can't use :has you might have to reconsider reorganizing your markup

<input type="checkbox" id="sports" class="checkbox">  
<label class="span-label" for="sports"> Sports</label>
<div class="dropup-content">
  ...
</div>

So that all elements are siblings of each other