You need to enable JavaScript to run this app. 为什么使用CSS动画时伪元素位置偏移?如何旋转不破坏原有造型
优惠活动
大模型
产品
解决方案
定价
更多

为什么使用CSS动画时伪元素位置偏移?如何旋转不破坏原有造型

问题原因

  • 伪元素的初始居中依赖transform: translate(-50%, -50%)属性实现,而CSS的transform动画默认会完全覆盖元素原有transform值,不会自动叠加。你定义的rotate关键帧中仅设置了scale和rotate属性,丢失了位移属性,动画触发后伪元素的居中规则失效,因此位置发生偏移破坏原有造型。

解决方案

你只需要调整动画关键帧,把原有的位移规则保留在transform中,让旋转效果和居中位移叠加生效即可。如果需要内外环旋转方向有差异,还可以给其中一个伪元素添加animation-direction: reverse配置,匹配对应动效。

修改后的完整代码

body {
  height: 100vh;
  padding: 0;
  margin: 0;
  position: relative;
}
@keyframes rotate {
  from {
    transform: translate(-50%, -50%) scale(1) rotate(0deg);
  }
  to {
    transform: translate(-50%, -50%) scale(1) rotate(360deg);
  }
}
div {
  background-color: #eee;
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #000000;
  font-size: 30px;
  font-weight: bold;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 0px solid;
  border-color: #ea2264 #ea2264 #ea2264 transparent;
  border-radius: 50%;

}
div::before {
  content: "";
  position: absolute;
  width: 200px;
  height: 200px;
  border: 10px solid;
  border-color: #ea2264 #ea2264 #ea2264 transparent;
  border-radius: 50%;
  left: 100px;
  top: 100px;
  transform: translate(-50%, -50%);
  animation-name: rotate;
  animation-duration: 1s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}
div::after {
  content: "";
  position: absolute;
  width: 220px;
  height: 220px;
  border: 10px solid;
  border-color: #2196f3 transparent #2196f3 #2196f3;
  border-radius: 50%;
  left: 100px;
  top: 100px;
  transform: translate(-50%, -50%);
  animation-name: rotate;
  animation-duration: 1s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}
<body>
  <div>Elzero</div>
</body>

内容的提问来源于stack exchange,提问作者fadi safou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 03:27:01