0

I'm having trouble making an SVG responsive. I've tried the solution offered to this question (Resize svg when window is resized in d3.js) but it is not working for me. No matter the settings, the SVG seems to maintain its aspect ratio. (I posted on this earlier. I'll delete that question once I sort out the issue).

Context: This is for a full screen D3 timeline running as an Electron desktop app. I've stripped out everything in order to provide a working example of the issue. The images below are from the Electron app but the behavior is the same in the browser: the SVG only scales proportionally and is cropped if the aspect ratio of the window doesn't match that of the SVG.

What I Want to Happen: Ideally, I'd like the "flex space" to be in the vertical dimension so that the SVG sizes to fit the width of the window and the height is scaled to fit.

Here is a working, editable bl.ock and the same block full page

I'm still learning JS and d3 – and the addition of CSS to handle responsiveness is getting very confusing, so any help is much appreciated.


1024 x 768 window size

enter image description here


1400 x 900 screen size: SVG is cropped

enter image description here

spring
  • 18,009
  • 15
  • 80
  • 160

1 Answers1

0

Well you could use

preserveAspectRatio="none"

But I suspect that is probably not what you want because it will stretch the content of the SVG.

body {
  margin: 0;
  padding: 0;
}

.svg-container {
  width: 100vw;
  height: 100vh;
  background-color: #ffff00;
}

.svg-content-responsive {
  display: block;
  background-color: #0000ff;
}
<div id="container" class="svg-container">

  <svg width="100%" height="100%" preserveAspectRatio="none" viewBox="0 0 984 728"
       class="svg-content-responsive" overflow="hidden">
    <rect x="20" y="20" width="944" height="50" style="fill: rgb(255, 0, 0);"></rect>
    <rect x="20" y="658" width="944" height="50" style="fill: rgb(0, 255, 0);"></rect>
  </svg>
  
</div>

Fiddle version

SVGs can't have parts that scale differently from the parent. So if you don't like the stretching, then you should consider using three separate SVGs - red, green, and the timeline scaled to fill the section between them.

Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181