Is it possible to change svg viewBox value using CSS?


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 ?


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; }
  <!-- 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" />

  <!-- following symbols will define our "views" -->
  <symbol id="small-view" viewBox="0 0 60 60">
    <use href="#scene"/>
  <symbol id="big-view"   viewBox="0 0 500 500">
    <use href="#scene"/>

  <!-- append all the views, CSS will determine which to display -->
  <use href="#small-view" id="small-use"/>
  <use href="#big-view"   id="big-use"/>
<p>Change the window's size to trigger the "change of viewBox"</p>

Answered By – Kaiido

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published