You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否将SVG的width、height属性设置在雪碧图的对应元素中?

方案1:用嵌套代替存储雪碧图图标

元素本身的width、height属性不会被标签继承,所以直接设置无效。你可以把雪碧图里的每个图标改为用独立的标签包裹,同时通过全局样式隐藏雪碧图内的所有子svg避免直接渲染,这样引用时会自动继承对应图标的宽高、viewBox属性。
雪碧图(icons.svg)代码示例:

<svg xmlns="http://www.w3.org/2000/svg">
  <!-- 隐藏雪碧图内所有图标,仅作资源存储用 -->
  <style>
    #icon-store > svg {
      display: none;
    }
  </style>
  <g id="icon-store">
    <svg id="icon-ellipsis" width="21" height="5" viewBox="0 0 21 5">
      <path d="M2.5 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Zm8 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Zm8 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Z" fill-rule="evenodd" />
    </svg>
    <!-- 其余图标按相同格式添加即可 -->
    <svg id="icon-close" width="16" height="16" viewBox="0 0 16 16">
      <!-- 图标路径 -->
    </svg>
  </g>
</svg>

业务侧引用代码可以简化为:

<svg>
  <use href="/icons.svg#icon-ellipsis"></use>
</svg>

无需额外添加宽高属性,会自动复用雪碧图内定义的参数。

方案2:配合CSS自定义属性实现

如果你习惯用管理图标,可以通过CSS变量把宽高定义在上,再配合全局样式自动赋值:
雪碧图代码示例:

<svg xmlns="http://www.w3.org/2000/svg">
  <symbol id="icon-ellipsis" style="--icon-w: 21px; --icon-h: 5px" viewBox="0 0 21 5">
    <path d="M2.5 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Zm8 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Zm8 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5Z" fill-rule="evenodd" />
  </symbol>
</svg>

全局添加CSS规则:

/* 给引用雪碧图的svg统一加类名icon,避免污染其他svg */
.icon {
  width: var(--icon-w, 24px);
  height: var(--icon-h, 24px);
}

业务侧引用代码:

<svg class="icon">
  <use href="/icons.svg#icon-ellipsis"></use>
</svg>

内容的提问来源于stack exchange,提问作者user11720384

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 03:09:02