【问题标题】:Keep object centre fixed whilst size changes在大小变化时保持对象中心固定
【发布时间】:2016-10-01 07:12:15
【问题描述】:

我有一个使用 CSS 关键帧扩展的圆圈,位置固定。问题是,随着圆改变大小,圆的中心移动(而左上角保持固定)。如何确保在动画期间中心是固定的?有没有办法指定 div 的“原点”,所以它不是左上角?

<div id="circle"></div>

#circle {
  position: fixed;
  background: #07F;
  border-radius: 50%;
  animation: expand linear 3s infinite;
  top: 10px;
  left: 10px;
}

@keyframes expand {
  0% {
    width: 100px;
    height: 100px;
  }
  100% {
    width: 500px;
    height: 500px;
  }
}

this JSFiddle

【问题讨论】:

    标签: css css-animations keyframe


    【解决方案1】:

    试试这个:

    #circle {
      position: fixed;
      background: #07F;
      border-radius: 50%;
      animation: expand linear 3s infinite alternate;
      top: calc(10px + 50px); /* 10px + (half of the initial height) */
      left: calc(10px + 50px); /* 10px + (half of the initial width) */
      transform: translate(-50%, -50%)
    }
    
    @keyframes expand {
      0% {
        width: 100px;
        height: 100px;
      }
      100% {
        width: 500px;
        height: 500px;
      }
    }
    &lt;div id="circle"&gt;&lt;/div&gt;

    【讨论】:

    • 不错,我正在考虑那个否定翻译,但缺少位置 +1 的 calc 部分
    • 实际上我最终切换到了这种方法,因为我后来在圆上添加了一个边框,并且缩放变换像素化了边框并改变了它的粗细
    【解决方案2】:

    另一种选择,您可以使用transform - scale 属性增加尺寸,然后使用transform-origin 使其居中:

    #circle {
      position: fixed;
      background: #07F;
      border-radius: 50%;
      animation: expand linear 3s infinite alternate;
      top: 10px;
      left: 10px;
      transform-origin: center;
      width: 100px;
      height: 100px;
    }
    @keyframes expand {
      0% {
        transform: scale(1);
      }
      100% {
        transform: scale(5);
      }
    }
    &lt;div id="circle"&gt;&lt;/div&gt;

    【讨论】:

    • 太好了,正是我想要的!
    • 很高兴帮助你@BinaryFunt
    猜你喜欢
    • 2015-02-12
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    相关资源
    最近更新 更多