htmlcsssvgresponsive-designresponsiveness

Resize SVG on Mobile


How can I resize my SVG Logo for responsiveness on Mobile?

Here's my Fiddle and my code is below:

body {
    background:black;
}

@media screen and (max-width: 500px) {
    svg {
        width:50%;
    }
}
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<svg version="1.1" preserveAspectRatio="xMinYMin meet" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
  <title>Logo</title>
  <desc>Created with Sketch.</desc>
  <defs></defs>
  <g id="Your-Score" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
    <g id="Desktop-Your-Score" sketch:type="MSLayerGroup" transform="translate(-23.000000, -24.000000)" font-weight="normal" font-family="Gill Sans" letter-spacing="1.16666663" font-size="28" sketch:alignment="middle" fill="#FFFFFF">
      <g id="Header" sketch:type="MSTextLayer">
        <g id="Primary-Nav-[home]-Copy">
          <g id="Logo" transform="translate(23.000000, 18.000000)">
            <text id="TOMORROW’S">
              <tspan x="0.0328778028" y="27">TOMORROW’S</tspan>
              <tspan x="36.2975262" y="58">SCORE</tspan>
            </text>
          </g>
        </g>
      </g>
    </g>
  </g>
</svg>


Solution

  • For scaling via the img element to work, the SVG image needs to have its width, height and viewBox attributes set inside it. Here is how that looks:

    <svg xmlns="http://www.w3.org/2000/svg"
            xmlns:xlink="http://www.w3.org/1999/xlink"
            width="70px" height="70px" viewBox="0 0 70 70">
        <circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/>
    </svg>
    

    When setting the width, height and viewBox property, you tell the browser what part of the virtual canvas to draw. The view box tells the upper left and lower right corner of the virtual canvas. Thus, if the image is scaled to a size bigger than that, the whole image is scaled up, instead of just making the virtual canvas bigger (resulting in white space next to the SVG shapes in the image).

    For more clarification search for viewBox property related to SVG.

    Always Set Image Width Via CSS Properties

    Do not use the width and height attributes of the img element. It will not give the desired effect. The browsers treat these attributes differently than the corresponding CSS properties.