如何使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
相关产品推荐
相关产品推荐

