能否将SVG的width、height属性设置在雪碧图的对应元素中?
方案1:用嵌套
<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自定义属性实现
如果你习惯用
雪碧图代码示例:
<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
相关产品推荐
相关产品推荐

