代码之家  ›  专栏  ›  技术社区  ›  Toolbox

窗体不绕中心轴(x,y)旋转

css
  •  0
  • Toolbox  · 技术社区  · 6 年前

    尽管我已经在CSS中设置了[变换原点:100%50%;],但是与x轴和y轴相比,表单并不围绕其中心旋转。

    问题: 如何使窗体从其中点精确地计数旋转。

        .box {
          background-color: pink;
          margin: 300px 0 0 300px;
          width: 200px;
          height: 200px;
        }
        
        .box {
          position: absolute;
          animation: spin 10s;
          animation-fill-mode: forwards;
        }
        
        .line-horizontal {
          background-color: black;
          width: 200px;
          height: 5px;
          margin: 100px 0 0 0;
        }
        
        .line-vertical {
          background-color: black;
          width: 5px;
          height: 200px;
          margin: -105px 0 0 100px;
        }
        
        @keyframes spin {
          from {
            transform:rotate(0deg);
            transform-origin: 100% 50%;
          }
          to {
            transform:rotate(360deg);
          }
        }
        
        
        <div class="box">
          <div class="line-horizontal"></div>
          <div class="line-vertical"></div>
        </div>
    1 回复  |  直到 6 年前
        1
  •  0
  •   Temani Afif    6 年前

    改变 tranform-origin 50% 50% 相反,这意味着中心在两个轴上,不要把它放在关键帧内,因为它会被设置动画。

    .box {
      background-color: pink;
      width: 200px;
      height: 200px;
    }
    
    .box {
      position: absolute;
      animation: spin 10s;
      animation-fill-mode: forwards;
      transform-origin: 50% 50%;
      /*center*/
    }
    
    .line-horizontal {
      background-color: black;
      width: 200px;
      height: 5px;
      margin: 100px 0 0 0;
    }
    
    .line-vertical {
      background-color: black;
      width: 5px;
      height: 200px;
      margin: -105px 0 0 100px;
    }
    
    @keyframes spin {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }
    <div class="box">
      <div class="line-horizontal"></div>
      <div class="line-vertical"></div>
    </div>

    如果需要相同的视觉效果,还可以像下面这样简化代码:

    .box {
      width: 200px;
      height: 200px;
      background:
        linear-gradient(#000,#000) center/100% 5px,
        linear-gradient(#000,#000) center/5px 100%,
        pink;
      background-repeat:no-repeat;
      animation: spin 10s forwards;
      transform-origin: 50% 50%; /* OR center*/
    }
    
    @keyframes spin {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }
    <div class="box">
    </div>