为何SVG脉冲动画中的圆形会偏移至右下角?
修复SVG脉冲动画的中心偏移问题
嘿,我看到你遇到了SVG脉冲动画偏移的问题——圆形跑到右下角去了,对吧?别担心,咱们一步步来搞定它:
问题根源分析
你的代码里有两个核心问题导致了偏移:
.pulse类用了position: fixed,这会让SVG脱离文档流,相对于整个浏览器视口定位,而不是它的父容器.container。虽然.container也是fixed,但fixed元素的子元素如果也是fixed,依然会相对于视口,不是父容器。- SVG元素的transform默认是基于整个SVG视口的,而不是圆形自身的中心,所以缩放动画会让圆形从左上角开始放大,看起来就偏移了。
修复后的完整代码
CSS 代码
@import url('https://fonts.googleapis.com/css?family=Lobster+Two'); h1 { font-family: 'Lobster Two', cursive; font-size: 5rem; color: #343434; z-index: 1; /* 确保标题在SVG上方,显式设置更稳妥 */ position: relative; /* 让z-index生效 */ } .container { position: fixed; z-index: 0; background-color: transparent; display: flex; align-items: center; justify-content: center; min-height: 100vh; overflow: hidden; width: 100%; /* 确保容器占满视口宽度 */ } .pulse { z-index: -1; position: absolute; /* 改为absolute,相对于.container定位 */ top: 50%; left: 50%; transform: translate(-50%, -50%); max-width: 30rem; width: 100%; /* 让SVG自适应容器宽度 */ height: auto; /* 保持SVG的宽高比 */ } .pulse circle { fill: #ff5154; transform: scale(0); opacity: 0; animation: pulse 2s forwards; transition-timing-function: cubic-bezier(0.5, 0.5, 0, 1); transform-box: fill-box; /* 让transform基于圆形自身的边界盒 */ transform-origin: center center; /* 明确设置缩放原点为中心 */ } .pulse circle:nth-child(2) { fill: #7fc6a4; animation: pulse 2s 1.75s forwards; /* 补上缺失的时间单位s */ transition-timing-function: cubic-bezier(0.5, 0.5, 0, 1); } .pulse circle:nth-child(3) { fill: #e5f77d; animation: pulse 2s 2.0s forwards; /* 补上缺失的时间单位s */ transition-timing-function: cubic-bezier(0.5, 0.5, 0, 1); } @keyframes pulse { 25% { opacity: 0.7; } 100% { transform: scale(1.05); opacity: 0; /* 让脉冲结束后淡出,动画更自然 */ } }
HTML 代码
<div class="container"> <h1>Pulse Animation</h1> <svg class="pulse" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <circle cx="512" cy="512" r="512"></circle> <circle cx="512" cy="512" r="512"></circle> <circle cx="512" cy="512" r="512"></circle> </svg> </div>
关键修改点说明
- 把
.pulse的position: fixed改为absolute:这样SVG会相对于父容器.container定位,而不是视口,确保它始终在容器中心。 - 添加
transform-box: fill-box和transform-origin: center center:让圆形的缩放动画以自身中心为原点,避免偏移。 - 修复了动画延迟的语法错误:你之前写的
1.75和2.00缺少时间单位s,这会导致动画不生效。 - 给
h1添加position: relative和z-index: 1:确保标题始终在SVG脉冲的上方,显式设置更可靠。 - 给
.container添加width: 100%:确保容器占满整个视口宽度,避免布局异常。
这样修改后,脉冲圆形就会始终保持在容器中心,并且在标题后方正常播放缩放动画啦!
内容的提问来源于stack exchange,提问作者Soup
相关产品推荐
相关产品推荐

