Checkbox checked is not working. HTML CSS

3.8k Views Asked by At

I am creating the sliding navbar using the checkbox method.

[But for only demo purpose i am changing the background to "blue"]

I used label and if checkbox is checked Its background changes to "blue". But It Is Not Working

Please Explain Why????

[See the code at https://codepen.io/adi45code/pen/abmxgQj]

HTML

<div class="position-right">
        <div class="nav-ele home">Home</div>
        <div class="nav-ele about">About</div>
        <div class="nav-ele services">Service</div>
        <div class="nav-ele goals">Goals</div>
        <div class="nav-ele contactus">Contact Us</div>
      </div>
      
      <!--Checkbox Toogle-->
     <input type="checkbox" id="checkbox"/>
    <label for="checkbox"><span>ColorRed</span></label>

CSS

  .position-right {
    flex-direction: column;
    background: #000000;
    width: 50%;
    height: 200px;
    text-align: center;
    transition: all .2s;
    position: absolute;
    left: -10px;
    color: red;
  }
  #checkbox:checked +.position-right {
    background: blue;
  }
  
span,input{
  position: absolute;
  right: 0;
  padding :10px;
}
input{
  top: 30px;
}
span:hover{
  color: red;
}
2

There are 2 best solutions below

0
On

The problem is that the ,,+,, selector only targets the next sibling of the element on the left side of the ,,+,, selector (in your case, your checkbox).

And because the label is the next sibling of your checkbox, your code wont work.

All you have to do is replace positions of your div and your checkbox, so that the div will come right after the checkbox (also, you have to put label before the checkbox, not after it).

Here is the fixed version, hope I helped you a little bit :)

https://codepen.io/Juka99/pen/vYXMoOY

0
On

You have to change the position of the input checkbox, because ,+, selector only target the next sibling

  .position-right {
    flex-direction: column;
    background: #000;
    width: 50%;
    height: 200px;
    text-align: center;
    transition: all .2s;
    position: absolute;
    left: -10px;
    color: red;
  }
  #checkbox:checked + .position-right {
    background: blue;
  }
  
span,input{
  position: absolute;
  right: 0;
  padding :10px;
}
input{
  top: 30px;
}
span:hover{
  color: red;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="style.css" title="" type="" />
</head>

<body>
      <!--layout--> 
   <!--Checkbox Toogle-->
     <label for="checkbox"><span>ColorBlue</span></label>
     <input type="checkbox" id="checkbox"/>
    
      <div class="position-right">
        <div class="nav-ele home">Home</div>
        <div class="nav-ele about">About</div>
        <div class="nav-ele services">Service</div>
        <div class="nav-ele goals">Goals</div>
        <div class="nav-ele contactus">Contact Us</div>
      </div>
</body>

</html>