1

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 ?

4
  • can you add the svg here? or refer this stackoverflow.com/questions/53699098/responsive-svg-viewbox
    – Viira
    Sep 29, 2021 at 5:03
  • as far as i know no
    – Edgar
    Sep 29, 2021 at 5:03
  • CSS can’t change attributes. Do you definitely want to change the viewbox as opposed to the dimensions of the viewed image?
    – A Haworth
    Sep 29, 2021 at 5:15
  • as i understand the css cannot change the viewBox
    – Edgar
    Sep 29, 2021 at 5:26

2 Answers 2

4

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>

-1

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.