给 SVG 设置 width="100%"
、height="100%"
,放在固定宽高的容器里,即可实现自适应宽高:
相关代码:
<div style="width: 160px;height: 80px;">
<svg width="100%" height="100%" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="2" y="2"
style="width: calc(100% - 4px);height: calc(100% - 4px);"
stroke="url(#linear)" stroke-width="2"/>
<defs>
<linearGradient id="linear" x1="0" y1="0" x2="1" y2="0">
<stop stop-color="#8F41E9"/>
<stop offset="1" stop-color="#578AEF"/>
</linearGradient>
</defs>
</svg>
</div>
rx
设置圆角stroke-dasharray
设置虚线stroke-dashoffset
设置偏移stroke-linecap
设置线条两端的形状
相关代码:
<div style="width: 160px;height: 80px;">
<svg width="100%" height="100%" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="2" y="2"
style="width: calc(100% - 4px);height: calc(100% - 4px);"
rx="4" stroke="url(#linear)"
stroke-width="2"
stroke-dasharray="4 4"
stroke-dashoffset="2"
stroke-linecap="round"/>
<defs>
<linearGradient id="linear" x1="0" y1="0" x2="1" y2="0">
<stop stop-color="#8F41E9"/>
<stop offset="1" stop-color="#578AEF"/>
</linearGradient>
</defs>
</svg>
</div>
SVG 可以内嵌样式,改变 stroke-dashoffset
即可
相关代码:
<div style="width: 160px;height: 80px;">
<svg width="100%" height="100%" fill="none" xmlns="http://www.w3.org/2000/svg">
<style>
.rect {
width: calc(100% - 4px);
height: calc(100% - 4px);
animation: move .3s infinite linear;
}
@keyframes move {
0% {
stroke-dashoffset: 0;
}
100% {
stroke-dashoffset: 14;
}
}
</style>
<rect class="rect" x="2" y="2" width="100%" height="100%"
rx="4" stroke="url(#linear)"
stroke-width="2"
stroke-dasharray="4 4"
stroke-dashoffset="2"
stroke-linecap="round"/>
<defs>
<linearGradient id="linear" x1="0" y1="0" x2="1" y2="0">
<stop stop-color="#8F41E9"/>
<stop offset="1" stop-color="#578AEF"/>
</linearGradient>
</defs>
</svg>
</div>
在实际应用中,我们把 SVG 单独存起来,作为容器的背景使用。
SVG 做边框:
.svg-border {
background: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' rx='5' fill='none' stroke='red' /></svg>");
}
.svg-line {
background: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><line x1='0' y1='100%' x2='100%' y2='100%' stroke='red' /></svg>");
}
https://mp.weixin.qq.com/s/pbvw7540X_mjcCHAeQf60g
https://mp.weixin.qq.com/s/VH2U-jqm3cXI0yQFrR3adQ
留言