简体   繁体   中英

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.

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 (ie, some whitespace is OK) then I could do:

body {
  background: url(/path/to/image.svg) no-repeat center center fixed;
  background-size: contain;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM