You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使Keyframe动画在窗口缩小时保持居中,实现响应式效果?

解决Keyframe动画在窗口缩小时无法保持居中的问题

问题根源

当前动画依赖固定像素值的left属性控制元素位置,这类值仅适配特定窗口宽度,窗口缩放后,固定位置会偏离页面居中区域,导致动画元素错位。

解决方案

改用transform: translateX()替代left实现动画,结合元素的基础居中布局,让动画始终基于页面中心偏移,不受窗口尺寸变化影响。

修改后的完整代码

CSS

body{
  background-color: black;
  text-align: center;  
}

h1{
  position: relative;
}

.main{
  color: pink;
}

#welcome{
  color: gold;
}

.selection{
  background-color: #1000df;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  font-size: 16px;
  margin: 4px 10px;
  cursor: pointer;
  border-radius: 5px;
}

#choose{
  color: white;
  max-width: 150px;
  position: relative;
  border-radius: 5px;
  /* 实现元素基础水平居中 */
  margin: 0 auto;
  animation-name: choose;
  animation-duration: 8s;
  animation-iteration-count: infinite;
}

@keyframes choose {
  /* 基于元素居中位置做左右偏移 */
  0%   {background-color:blue; transform: translateX(-130px);}
  25%  {background-color:pink; transform: translateX(130px);}
  50%  {background-color:green; transform: translateX(-130px);}
  75%  {background-color:orange; transform: translateX(130px);}
  100% {background-color:blue; transform: translateX(-130px);}
}

HTML

<body>
  <div class = "main">
<h1 id = "welcome">Welcome To the Ancient Game of Lapis....Papyrus....Scalpellus!</h1>

<h4 id = "choose">choose wisely...</h4>

<div id="choice">
  <button class="selection" id="lapis">Lapis</button>
  <button class="selection" id="papyrus">Papyrus</button>
  <button class="selection" id="scalpellus">Scalpellus</button>
  </div>

<div id="results-container">
<h2 id="results"></h2>
</div>
  </div>
</body>

额外优化建议

如果希望动画偏移距离适配不同屏幕尺寸,可将130px替换为视窗单位(如10vw),实现响应式的偏移效果。

内容的提问来源于stack exchange,提问作者Taariq Elliott

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:31:00