英文:
How to size a SVG icon via a <use> element like an image
问题
在我的HTML文档中,我有一个包含许多带有id属性的<svg>元素,例如icon-x。
然后,我想像这样重用这些图标:
<div class=container>
<svg><use xlink:href=#icon-x /></svg>
</div>
然而,在这种情况下,源SVG中的图标可能具有不同的大小。我希望它们适应div.container的大小,但容器中的SVG周围有空白。
我该如何告诉它要使用我指向的那个东西,并知道那个东西定义了<svg>的大小,这样当我像这样使用CSS时 .container svg { width: 100%; height: auto;} 它就像使用<img>标签一样工作?
英文:
In my HTML document I have an <svg> that includes many items with id attributes like icon-x.
I then want to reuse these icons like
<div class=container>
<svg><use xlink:href=#icon-x /></svg>
</div>
However, the icons in this case may be different sizes within the source SVG. I want them to fit the div.container, but the svg in the container has whitespace around it.
How can I tell it to <use> the thing I point to, and know that that thing defines the size of the <svg>, so that then when I do CSS like .container svg { width: 100%; height: auto;} it works as it would an <img> tag?
答案1
得分: 2
-
icon-x必须是一个符号或带有 viewBox 属性的嵌套 svg。 -
当使用
icon-x时,您需要为<use>元素指定width和height。您还可以为<use>指定不同的位置(x 和 y 属性)或不同的填充。
在下一个示例中,我正在使用一个 <symbol>。您可以选择使用嵌套的 svg 替代。在这种情况下,您可能希望将其放在 <defs> 中。
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
svg{
border:solid;
width:90vh;
}
<!-- language: lang-html -->
<svg viewBox="0 0 240 240">
<symbol id="icon-x" viewBox="0 0 24 24">
<path d="M21 16v-2l-8-5v-5.5c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v5.5l-8 5v2l8-2.5v5.5l-2 1.5v1.5l3.5-1 3.5 1v-1.5l-2-1.5v-5.5l8 2.5z"></path>
</symbol>
<use xlink:href="#icon-x" x="10" y="10" width="150" height="150"/>
<use xlink:href="#icon-x" x="120" y="120" width="50" height="50" fill="blue"/>
</svg>
<!-- end snippet -->
英文:
-
The
icon-xmust be a symbol or a nested svg with a viewBox attribute -
When using the
icon-xyou give the<use>element anwidthand aheight.
You can also give the<use>a different position (x and y attributes) or a different fill.
In the next example I'm using a <symbol>. You can choose to use a nested svg instead. In this case you may want to put it in a <defs>
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
svg{
border:solid;
width:90vh;
}
<!-- language: lang-html -->
<svg viewBox="0 0 240 240">
<symbol id="icon-x" viewBox="0 0 24 24">
<path d="M21 16v-2l-8-5v-5.5c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v5.5l-8 5v2l8-2.5v5.5l-2 1.5v1.5l3.5-1 3.5 1v-1.5l-2-1.5v-5.5l8 2.5z"></path>
</symbol>
<use xlink:href="#icon-x" x="10" y="10" width="150" height="150"/>
<use xlink:href="#icon-x" x="120" y="120" width="50" height="50" fill="blue"/>
</svg>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论