Figma导出的SVG在网页上显示错位,如何解决?

设计师振岚 阅读 38

最近在用Figma导出SVG图标到项目里,但发现有些图标在页面上显示位置总是不对,比如文字和图形不在同一水平线。我按设计稿导出的SVG尺寸是24×24,但实际渲染时却溢出容器了。

我尝试用JS动态插入SVG,设置了width/height样式,但没用:


const svgContainer = document.getElementById('icon-wrapper');
const svgUrl = 'path/to/icon.svg';

fetch(svgUrl)
  .then(response => response.text())
  .then(svgData => {
    const parser = new DOMParser();
    const svg = parser.parseFromString(svgData, 'image/svg+xml').documentElement;
    svg.setAttribute('style', 'width:24px;height:24px');
    svgContainer.appendChild(svg);
  });

检查原始SVG代码发现有viewBox属性,但数值和设计稿画板尺寸不一致。是不是Figma导出时需要特别设置?或者代码里需要处理viewBox和尺寸的关系?

我来解答 赞 3 收藏
二维码
手机扫码查看
1 条解答
书生シ家轩
Figma导出的SVG显示错位,大概率是 viewBox 和实际尺寸没对齐。省事的话直接在导出的SVG标签上加 preserveAspectRatio="xMidYMid meet",再配合 width 和 height 设置成 1em 或具体像素。这样在网页上会按比例居中对齐,不会溢出容器。

如果不想改SVG内容,代码里也可以动态处理,比如:

fetch(svgUrl)
.then(response => response.text())
.then(svgData => {
const parser = new DOMParser();
const svg = parser.parseFromString(svgData, 'image/svg+xml').documentElement;
svg.setAttribute('width', '24');
svg.setAttribute('height', '24');
svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
svgContainer.appendChild(svg);
});
点赞 5
2026-02-06 13:01