alex
alex

Reputation: 7601

How to make the following SVG fit its parent (horizontally and vertically)?

Live reproduction: https://codepen.io/alexcheninfo/pen/dZqmLv

This is the SVG:

<svg class="line-chart" width="860" height="405"></svg>

This is the CSS of the container:

.common-section {
  position: relative;
  width: 100%;
  background-color: red;
  margin-bottom: 30px;
}

Screenshot:

enter image description here

Upvotes: 0

Views: 34

Answers (1)

Ted Whitehead
Ted Whitehead

Reputation: 1826

Two things:

  1. You are missing the viewBox attribute.

  2. Adding preserveAspectRatio="xMidYMid meet" will maintain the original aspect ratio as the image scales. If you need to support IE 11 or below, then you either need to use CSS to preserve the aspect ratio (see http://www.mademyday.de/css-height-equals-width-with-pure-css.html) or you could use JS to automate that for you (see https://gist.github.com/Heydon/369185d08d9ce2426f01863625e95525).

Here’s a working version of your CodePen demo:
https://codepen.io/tedw/pen/YEOLPr?editors=1100

FWIW, here are some good resources regarding scaling SVGs:

Hope that helps!

UPDATE:

I imported your SVG into Illustrator and did some optimization (including running it through https://jakearchibald.github.io/svgomg/). Here’s the final code:

<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 522 213" preserveAspectRatio="xMidYMid meet" style="font-family: Helvetica, sans-serif; font-size: 6px;" fill="#000">
  <g transform="translate(20 60)">
    <path d="M490 128.2l-71.2 5-71-.3L63-57l-71 176.3"/>
    <circle cx="489.9" cy="128.2" r="3"/>
    <circle cx="418.8" cy="133.4" r="3"/>
    <circle cx="347.7" cy="132.9" r="3"/>
    <circle cx="63.2" cy="-57" r="3"/>
    <circle cx="-7.9" cy="119.3" r="3"/>
  </g>
  <text transform="translate(498.37 210.08)">17/10/18</text>
  <text transform="translate(427.266 210.08)">17/10/17</text>
  <text transform="translate(356.16 210.08)">17/10/16</text>
  <text transform="translate(71.735 210.08)">17/10/12</text>
  <text transform="translate(.85 210.08)">17/10/11</text>
  <text transform="translate(0 201.83)">0</text>
  <text transform="translate(0 179.485)">100</text>
  <text transform="translate(0 157.137)">200</text>
  <text transform="translate(0 134.793)">300</text>
  <text transform="translate(0 112.47)">400</text>
  <text transform="translate(0 90.123)">500</text>
  <text transform="translate(0 67.78)">600</text>
  <text transform="translate(0 45.435)">700</text>
  <text transform="translate(0 23.095)">800</text>
  <g fill="none" stroke="#000">
    <path d="M12 200.6h498"/>
    <path d="M12 178.3h498"/>
    <path d="M12 156h498"/>
    <path d="M12 133.6h498"/>
    <path d="M12 111.3h498"/>
    <path d="M12 89h498"/>
    <path d="M12 66.6h498"/>
    <path d="M12 44.3h498"/>
    <path d="M12 21.8h498"/>
  </g>
</svg>

Upvotes: 1

Related Questions