Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I scale SVG width with CSS?

I am using Google's Charts js library. It works great, and makes terrific graphs for our data.

Unfortunately, due to how it is created, it is not responsive, so if the screen size changes, it doesn't change to match. I got that one solved via a redraw function set to window.onresize, so that is fixed.

It seems that printing is not considered a resize event and so redraw isn't called. I have a print-only css molding the rest of the page to look great when printed, but the chart stays the same size as it was in the browser window. I can make the window smaller, and it prints without screwing up the page scaling, but that isn't a real solution.

I have tried:

adding svg{width:100%;} to print.css - no good

I have not Tried:

making the graphs a set size that WILL print nicely - this seems like a hack, and I would prefer not to do it if at all possible.

EDIT

One modification: the Google Charts API creates the svg as an <svg> in a <div>. It is not a background image.

like image 465
Christian Smith Avatar asked Nov 11 '22 19:11

Christian Smith


1 Answers

This is a referral:

https://developer.mozilla.org/en-US/docs/Web/CSS/Scaling_of_SVG_backgrounds

and my solution:

After some trial-and-error, this is what I found.

Adding (to the original CSS):

html {
   height: 100%
}

delivered exactly what I was looking for in the original spec.

Additionally, if I wanted the image to be center when it was cropped, I could use:

html {
    background: url(path/to/image.jpg) no-repeat center center fixed;
    background-size: cover;
}

Lastly, if I wanted it to be centered, always maintain the aspect ratio, but NOT be cropped (i.e., some whitespace is OK) then I could do:

body {
  background: url(/path/to/image.svg) no-repeat center center fixed;
  background-size: contain;
}
like image 92
Mr. Zoidberg Avatar answered Nov 14 '22 23:11

Mr. Zoidberg