当窗口宽度为660px时,我想使用CSS更改viewBox的svg值。viewBox="0 0 230 87" => viewBox="0 0 100 87"
.是否可以使用CSS更改svg viewBox值?
您只能通过CSS更改表示属性。viewBox
不是其中之一。
然而,您可以使用CCD_ 3元素来定义";视图";在现场
事实上,<symbol>
确实有一个viewBox
属性,所以您可以使用此元素指向整个场景,然后每个这样的"使用一个<use>
元素;视图";并在显示此<use>
时通过CSS进行控制:
svg {
border: 1px solid;
border-color: yellow;
}
@media (max-width:500px) {
svg { border-color: green; }
#small-use { display: block; }
#big-use { display: none; }
}
@media (min-width:501px) {
#small-use { display: none; }
#big-use { display: block; }
}
<svg>
<!-- we wrap the whole scene in one symbol -->
<symbol id="scene">
<rect fill="blue" x="0" y="0" width="500" height="500"/>
<rect fill="red" x="0" y="0" width="50" height="50" />
</symbol>
<!-- following symbols will define our "views" -->
<symbol id="small-view" viewBox="0 0 60 60">
<use href="#scene"/>
</symbol>
<symbol id="big-view" viewBox="0 0 500 500">
<use href="#scene"/>
</symbol>
<!-- append all the views, CSS will determine which to display -->
<use href="#small-view" id="small-use"/>
<use href="#big-view" id="big-use"/>
</svg>
<p>Change the window's size to trigger the "change of viewBox"</p>
如果要更改SVG宽度,可以在svg
标签上设置width
属性
<svg width="40" height="40" viewBox="0 0 40 40">...</svg>
或者,你可以在上面添加CSS样式。
<svg viewBox="0 0 40 40" style="width:80px; height: 80px">...</svg>
如果您编辑viewBox
,您的SVG形状可能会被破坏。