Weird behavior when rotating an element on hover

前端 未结 2 1498
一向
一向 2020-12-22 05:23

Given these two examples.

Using Hover

2条回答
  •  梦毁少年i
    2020-12-22 05:31

    You need to set an initial rotate(0), so there can be animation between the two states. Set the div's initial transform to:

    transform: translateX(-50%) rotate(0);
    

    Transition:

    div {
      position: absolute;
      width: 150px;
      height: 40px;
      background: orange;
      left: 50%;
      top: var(--top);
      transition: transform 2s;
      transform: translateX(-50%) rotate(0);
      text-align: center;
      line-height: 40px;
      font-size: 1.2em;
    }
    
    div:hover {
      transform: translateX(-50%) rotate(var(--deg));
    }
    
    div:nth-child(1) {
      --deg: 180deg;
      --top: 20%;
    }
    
    div:nth-child(2) {
      --deg: -180deg;
      --top: 40%;
    }
    
    div:nth-child(3) {
      --deg: 360deg;
      --top: 60%;
    }
    
    body {
      overflow: hidden;
    }
    180deg
    -180deg
    360deg

    Animation:

    div {
      position: absolute;
      width: 150px;
      height: 40px;
      background: orange;
      left: 50%;
      top: var(--top);
      transform: translateX(-50%) rotate(0);
      text-align: center;
      line-height: 40px;
      font-size: 1.2em;
      animation: rotate 2s linear 2s forwards;
    }
    
    @keyframes rotate {
      to {
        transform: translateX(-50%) rotate(var(--deg));
      }
    }
    
    div:nth-child(1) {
      --deg: 180deg;
      --top: 20%;
    }
    
    div:nth-child(2) {
      --deg: -180deg;
      --top: 40%;
    }
    
    div:nth-child(3) {
      --deg: 360deg;
      --top: 60%;
    }
    
    body {
      overflow: hidden;
    }
    180deg
    -180deg
    360deg

提交回复
热议问题