是的,您可以在 svg 中使用百分比。
对于基本形状,它非常简单。你可以把你的主要矩形写成
<rect x="0" y="5" width="100%" height="10"/>
您的第二个矩形更简单,因为它始终位于 0,0
<rect x="0" y="0" width="10" height="20"/>
但是箭头在路径和多边形中存在问题,您不能使用百分比。要解决此问题,有一个两步解决方案。
先把路径放在一个符号元素中:
<symbol id="arrow" viewBox="0 0 20 20" width="20" height="20">
<path d="M0,0L20 10L0 20z" />
</symbol>
现在您可以像定位矩形一样定位此符号...简单...
<use xlink:href="#arrow" x="100%" y="0" width="20" height="20"/>
但是现在您的箭头开始 100% 并且完全在您的视口之外。你可以只设置溢出:在你的 svg 上可见并完成它,但这不是我们想要的......我们希望箭头以 100% 结束。但这也很简单,我们知道箭头是 20px 宽。所以只需将 use 翻译回 20px:
<use xlink:href="#arrow" x="100%" y="0" width="20" height="20" transform="translate(-20 0)"/>
使用这种方法,您可以根据百分比将任何形状定位在任何位置...
为了将它全部扭曲,您的完整 svg 现在看起来像这样:
<svg id="svg" height="20px" xmlns:xlink="http://www.w3.org/1999/xlink">
<symbol id="arrow" viewBox="0 0 20 20" width="20" height="20">
<path d="M0,0L20 10L0 20z" />
</symbol>
<g id="Group" fill="#5FDCC7">
<rect x="0" y="5" width="100%" height="10" transform="translate(-20 0)" />
<rect x="0" y="0" width="10" height="20" />
<use xlink:href="#arrow" width="20" height="20" x="100%" y="0" transform="translate(-20 0)" />
</g>
</svg>
这是一个使用这个 svg 的 sn-p,具有 3 种不同的宽度:
svg:nth-of-type(1) {
width: 100px
}
svg:nth-of-type(2) {
width: 200px
}
svg:nth-of-type(3) {
width: 300px
}
<svg height="20px" xmlns:xlink="http://www.w3.org/1999/xlink">
<symbol id="arrow" viewBox="0 0 20 20" width="20" height="20">
<path d="M0,0L20 10L0 20z" />
</symbol>
<g id="Group" fill="#5FDCC7">
<rect x="0" y="5" width="100%" height="10" transform="translate(-20 0)" />
<rect x="0" y="0" width="10" height="20" />
<use xlink:href="#arrow" width="20" height="20" x="100%" y="0" transform="translate(-20 0)" />
</g>
</svg>
<br/>
<svg height="20px" xmlns:xlink="http://www.w3.org/1999/xlink">
<symbol id="arrow" viewBox="0 0 20 20" width="20" height="20">
<path d="M0,0L20 10L0 20z" />
</symbol>
<g id="Group" fill="#5FDCC7">
<rect x="0" y="5" width="100%" height="10" transform="translate(-20 0)" />
<rect x="0" y="0" width="10" height="20" />
<use xlink:href="#arrow" width="20" height="20" x="100%" y="0" transform="translate(-20 0)" />
</g>
</svg>
<br/>
<svg height="20px" xmlns:xlink="http://www.w3.org/1999/xlink">
<symbol id="arrow" viewBox="0 0 20 20" width="20" height="20">
<path d="M0,0L20 10L0 20z" />
</symbol>
<g id="Group" fill="#5FDCC7">
<rect x="0" y="5" width="100%" height="10" transform="translate(-20 0)" />
<rect x="0" y="0" width="10" height="20" />
<use xlink:href="#arrow" width="20" height="20" x="100%" y="0" transform="translate(-20 0)" />
</g>
</svg>