我需要多次重用一些SVG图标,为了避免重复,我将它们放在一个<defs>标记中,然后在<use>中重用它们。但是,我只想通过定义高度来调整图标的大小,我希望宽度能够自动调整,但是它不能工作,我无法找到任何解决方案。有什么可能使宽度动态吗?
svg {
display: block;
margin: 1rem;
padding: 1rem;
background: rebeccapurple;
color: white;
}<svg style="display: none" >
<defs>
<symbol id="icon" viewBox="0 0 384 512">
<path fill="currentColor" stroke="none" d="m384 192c0 87.4-117 243-168.3 307.2-12.3 15.3-35.1 15.3-47.4 0-52.2-64.2-168.3-219.8-168.3-307.2 0-106.04 85.96-192 192-192 106 0 192 85.96 192 192z"/>
</symbol>
</defs>
</svg>
<!-- Doesn't work, the width is arbitrarily set to 300px. -->
<svg height="1rem">
<use href="#icon" />
</svg>
发布于 2022-07-01 22:24:43
CSS aspect-ratio允许您在指定高度或宽度时达到一致的比率。在您的示例中,可以将aspect-ratio设置为svg viewbox比率: 384/512;
请参阅https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio
工作片段:
svg {
display: block;
aspect-ratio: 384/512;
margin: 1rem;
padding: 1rem;
background: rebeccapurple;
color: white;
}<svg style="display: none" >
<defs>
<symbol id="icon" viewBox="0 0 384 512">
<path fill="currentColor" stroke="none" d="m384 192c0 87.4-117 243-168.3 307.2-12.3 15.3-35.1 15.3-47.4 0-52.2-64.2-168.3-219.8-168.3-307.2 0-106.04 85.96-192 192-192 106 0 192 85.96 192 192z"/>
</symbol>
</defs>
</svg>
<!-- Doesn't work, the width is arbitrarily set to 300px. -->
<svg height="1rem">
<use href="#icon" />
</svg>
https://stackoverflow.com/questions/72834684
复制相似问题