简体   繁体   中英

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:

在此处输入图像描述

  1. Arrow facing up when checked:

在此处输入图像描述

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM