I want to change the svg value of the viewBox using CSS when the window width is 660px.
viewBox="0 0 230 87" => viewBox="0 0 100 87".Is it possible to change svg viewBox value using CSS ?
CodePudding user response:
You can only change presentation attributes through CSS. viewBox is not one of these.
What you can do however is to use <symbol> elements to define "views" over the scene.
Indeed, <symbol> does have a viewBox attribute, so you can use this element to point to the whole scene, and then use one <use> element per such "view" and control via CSS when this <use> is displayed:
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>
CodePudding user response:
If you want to change SVG width, you can set width property on svg tag
<svg width="40" height="40" viewBox="0 0 40 40">...</svg>
or, you can add CSS style on it.
<svg viewBox="0 0 40 40" style="width:80px; height: 80px">...</svg>
If you edit viewBox, your SVG shape might be destroyed.
