htmlcsscheckboxrotationunchecked

Manipulate a checkbox to have CSS rotate when unchecked


I made a mobile navigation with a checkbox to have a dropdown menu. When the checkbox is checked (the nav is 'open'), it rotates 180deg, so the arrow faces upwards. I would like to have the same effect backwards when I click on it. The problem is that I do not know how to reach a state like checkbox:unchecked (which doesn't make sense, because a checkbox is unchecked by default else you do not define checked in html) or should I use something like :after?

I tried something like this but did not work ( I guess I am not using right syntax)

     #menu-toggle:checked~label i  {    /*Rotates when checked*/
     
         transform: rotate(180deg);
         transition: all ease-in-out .3s
      }

     #menu-toggle:checked:after~label i  {  /*My trial to reach the same reverse rotation when unchecked*/
         transform: rotate(-180deg);
         transition: all ease-in-out .3s
      }

1.Arrow in default state:

enter image description here

  1. Arrow facing up when checked:

enter image description here

Only CSS, no JS or jQuery now. Thank you!


Solution

  • It's actually pretty simple, by default a transition on an element makes sure that any kind of change goes smoothly both ways, from initial to desired and backwards. You only need to rotate when checked:

    #menu-toggle ~ label i {
      transition: all ease-in-out .3s;
    }
    
    #menu-toggle:checked ~ label i {
      transform: rotate(-180deg);
    }
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    
    <input type="checkbox" id="menu-toggle">
    <label>
      <i class="fa fa-angle-down" aria-hidden="true"></i>
    </label>