【问题标题】:I can't position a div in CSS without it messing up the animation我不能在 CSS 中放置一个 div 而不会弄乱动画
【发布时间】:2021-09-06 01:27:07
【问题描述】:

我尝试制作一个旋转正方形,它会在旋转 180 度时变成椭圆形,我遇到的问题是,当正方形旋转时,它会向左移动,因此左上角始终保持不变。 Visualization of the problem。我认为这是因为我的动画改变了正方形的宽度:

`@keyframes squarestuff {
  50% {
    transform: rotate(180deg);
    width: 5rem;
    border-radius: 50%;
  }`

【问题讨论】:

    标签: html css css-animations


    【解决方案1】:

    尝试添加这个

    @keyframes squarestuff {
      50% {
        transform: rotate(180deg);
        width: 5rem;
        border-radius: 50%;
        transform-origin:center center;
      }
    

    因为它变换中心并围绕新中心旋转。 如果还有问题,让div的宽度包含正方形作为正方形的宽度

    【讨论】:

    • 请点击“tic”确认答案是否正确。谢谢
    【解决方案2】:

    就是这样: https://jsfiddle.net/0pz1tv7q/

    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    
    div {
      height: 100px;
      width: 100px;
      border: 5px solid black;
      background: red;
      position: absolute;
      animation: mymove 5s;
      animation-fill-mode: forwards;
    }
    
    @keyframes mymove {
        100% {
        transform: rotate(180deg);
        width: 25%;
        border-radius: 50%;
      }
    }
    </style>
    </head>
    <body>
    
    <h2>Square CSS</h2>
    <div></div>
    
    </body>
    </html> 
    

    【讨论】:

      【解决方案3】:

      假设您希望椭圆的中心保持在“正方形”的中心(即不移动),那么您可以使用变换比例而不是更改宽度。

      这个 sn-p 旋转正方形,使其中心始终在同一位置,并将椭圆添加为伪元素,以便您看到发生了什么并且中心不会移动:

      div {
        width: 10rem;
        height: 10rem;
        background-color: magenta;
        animation: squarestuff 5s linear infinite;
        transform-origin: center center;
        position: relative;
      }
      
      @keyframes squarestuff {
        50% {
          transform: rotate(180deg);
        }
      }
      
      div::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%) scale(1, 1);
        background: blue;
        width: 10rem;
        height: 10rem;
        animation: square2oval 5s linear infinite;
        z-index: 1;
        display: inline-block;
      }
      
      @keyframes square2oval {
        50% {
          transform: translate(-50%, -50%) scale(0.5, 1);
          border-radius: 50%;
        }
      }
      &lt;div&gt;&lt;/div&gt;

      【讨论】:

        猜你喜欢
        • 2014-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-13
        • 2017-10-18
        • 1970-01-01
        相关资源
        最近更新 更多