如何在CSS中让多个类名共用同一@keyframes关键帧
问题根源
你遇到的核心问题是CSS原生@keyframes规则不支持通过逗号分隔同时定义多个动画名称,这种写法属于无效语法,因此两个元素的动画均无法生效。
可行解决方案
方案1:共用同一个动画名称(原生CSS最简方案)
直接让两个类使用同一个动画名称,各自仅定义差异化的动画属性(如延迟、播放方向),核心动画逻辑只编写一次。
修改后的完整代码
/* 所有元素基础样式 */ div { width: 100px; height: 100px; background-color: red; animation-duration: 4s; /* 修正:必须添加单位`s`,原代码的`4`为无效值 */ animation-iteration-count: infinite; } /* 第三、第四个元素共用的基础定位 */ .anim_3, .anim_4 { position: relative; } /* 第三个元素:仅定义差异化属性 */ .anim_3 { animation-name: anim_shared; /* 共用同一个动画名称 */ animation-delay: 1s; } /* 第四个元素:仅定义差异化属性 */ .anim_4 { animation-name: anim_shared; /* 共用同一个动画名称 */ animation-delay: 2s; animation-direction: reverse; } /* 核心动画逻辑:只编写一次 */ @keyframes anim_shared { 0% { background-color: red; left: 0px; top: 0px; } 25% { background-color: yellow; left: 200px; top: 0px; } 50% { background-color: blue; left: 200px; top: 200px; } 75% { background-color: green; left: 0px; top: 200px; } 100% { background-color: red; left: 0px; top: 0px; } }
<h1>CSS Animation</h1> <p> <b>Note</b> Both the background-color and the position of the element changes </p> <div class="anim_3">Third Animation</div> <p> <b>Note:</b> the animation runs in the reverse direction </p> <div class="anim_4">Fourth Animation</div>
方案2:使用CSS变量复用动画关键帧(进阶场景)
如果后续需要对某个动画做细微调整,可以用CSS变量抽离关键帧中的可配置项,给不同类赋值不同变量值,核心动画逻辑依然只写一次。
示例代码(自定义移动距离)
div { width: 100px; height: 100px; background-color: red; animation-duration: 4s; animation-iteration-count: infinite; --move-distance: 200px; /* 默认移动距离 */ } .anim_3, .anim_4 { position: relative; animation-name: anim_shared; } .anim_3 { animation-delay: 1s; } .anim_4 { animation-delay: 2s; animation-direction: reverse; --move-distance: 150px; /* 自定义移动距离 */ } @keyframes anim_shared { 0% { background-color: red; left: 0px; top: 0px; } 25% { background-color: yellow; left: var(--move-distance); top: 0px; } 50% { background-color: blue; left: var(--move-distance); top: var(--move-distance); } 75% { background-color: green; left: 0px; top: var(--move-distance); } 100% { background-color: red; left: 0px; top: 0px; } }
内容的提问来源于stack exchange,提问作者Nelson Ndiy
相关产品推荐
相关产品推荐

