如何在页面居中叠加三个SVG并支持单独@keyframes动画?
解决方案:让多个SVG在页面中心叠加并支持单独动画
原代码的问题在于每个SVG分散在独立容器中,定位上下文混乱,导致无法精准叠加。我们可以通过统一的定位容器来解决这个问题,既保证整体在页面中心,又能让每个SVG独立调整位置、支持动画。
修改后的代码实现
HTML 代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Graphic-center</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="graphic"> <!-- 统一容器包裹所有SVG,提供定位参照 --> <div class="svg-container"> <img src="stackoverflow/SVG/triangle.svg" class="triangle" width="150px"/> <img src="stackoverflow/SVG/circle.svg" class="circle" width="150px"/> <img src="stackoverflow/SVG/rectangle.svg" class="rectangle" width="150px"/> </div> </div> </body> </html>
CSS 代码
*{ margin: 0; padding: 0; box-sizing: border-box; } .graphic{ height: 100vh; width: 100vw; background-color: palegreen; /* 让容器在页面中心 */ display: grid; place-items: center; } /* 核心容器:作为所有SVG的定位参照 */ .svg-container{ position: relative; /* 尺寸与SVG一致,确保定位精准 */ width: 150px; /* 根据你的三角形SVG实际高度调整,比如假设是130px */ height: 130px; } .triangle{ position: absolute; /* 默认与容器左上角对齐,作为基础层 */ top: 0; left: 0; } .circle{ position: absolute; /* 根据需求调整位置,让圆形在三角形内部 */ top: 20px; left: 20px; } .rectangle{ position: absolute; /* 让矩形在三角形底部,保留空隙 */ top: 135px; left: 0; }
关键说明
- 统一定位上下文:
.svg-container设置position: relative,所有内部SVG的absolute定位都会以这个容器为参照,不会乱跑。 - 整体居中:
.graphic通过grid布局让容器固定在页面中心,无需额外调整。 - 支持单独动画:每个SVG都是独立的绝对定位元素,后续可以直接用
@keyframes给单个元素加动画,比如:
@keyframes rotateCircle { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .circle{ animation: rotateCircle 3s linear infinite; }
内容的提问来源于stack exchange,提问作者Jen
相关产品推荐
相关产品推荐

