如何为一组HTML元素同步应用CSS shimmer动画
实现一组HTML元素的同步Shimmer动画
要实现类似background-clip: text但作用于HTML元素的同步shimmer动画,核心思路是将动画放在父容器上,通过CSS Masking将动画裁剪到子元素的形状和位置,这样整个动画是统一运行的,自然保持同步。
实现步骤
- 把所有需要同步动画的元素放在同一个父容器中
- 父容器设置基础灰色背景,通过伪元素实现shimmer动画
- 使用CSS
mask属性将伪元素的动画精准裁剪到各个子元素的形状和位置
完整代码
CSS
.shimmer-box { width: 300px; height: 75px; margin: 20px 20px; } .animation { background: linear-gradient(-45deg, #eee 40%, #fafafa 50%, #eee 60%); background-size: 300%; animation: shimmer 1000ms linear infinite; } @keyframes shimmer { 0% { background-position-x: 100%; } 100% { background-position-x: 0%; } } .flex-row { display: flex; align-items: center; gap: 12px; } .circle { width: 30px; height: 30px; border-radius: 50%; } .short-row { height: 30px; flex: 1; border-radius: 8px; } .body-box { margin-top: 12px; width: 342px; height: 100px; border-radius: 8px; } .container { display: inline-block; } /* 同步动画容器样式 */ .shimmer-container { background-color: #e2e2e2; position: relative; overflow: hidden; padding: 0 0 12px; } .shimmer-container::before { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: linear-gradient(-45deg, #eee 40%, #fafafa 50%, #eee 60%); background-size: 300%; animation: shimmer 1000ms linear infinite; /* 通过mask裁剪动画到子元素区域 */ mask: radial-gradient(circle 15px at 15px 15px, black 98%, transparent) 0 0 / 30px 30px, linear-gradient(black, black) 42px 0 / calc(50% - 48px) 30px, linear-gradient(black, black) 0 42px / 342px 100px; mask-repeat: no-repeat; } .gray { background-color: #e2e2e2; }
HTML
<h4>单个元素的动画效果</h4> <div class="shimmer-box animation"></div> <h4>每个元素单独加动画会不同步</h4> <div class="container"> <div class="flex-row"> <div class="circle gray animation"></div> <div class="short-row gray animation"></div> <div class="short-row gray animation"></div> </div> <div class="body-box gray animation"></div> </div> <h4>同步的shimmer动画效果</h4> <p>光影会连贯地穿过所有元素</p> <div class="container shimmer-container"> <div class="flex-row"> <div class="circle"></div> <div class="short-row"></div> </div> <div class="body-box"></div> </div>
原理说明
- 父容器
.shimmer-container设置灰色背景作为基础样式,伪元素::before承载shimmer动画背景 mask属性通过多个渐变组合,精准匹配每个子元素的位置、尺寸和形状,只让动画在这些区域显示- 动画只在伪元素上运行一次,自然实现所有元素的同步光影效果
内容的提问来源于stack exchange,提问作者jmancherje
相关产品推荐
相关产品推荐

