Search code examples
cssimagesvgbackground-image

SVG doesn't respect background-size 100% 100%


I have this SVG image that I would like to cover a complete container, keeping its distinctive edges. background-size: 100% 100%; seems like the perfect choice and while it works for regular images, it doesn't work in this case. Why?

(jpeg taken from James' answer)

html, body {
  background-color: #ddd;
}
.container {
  margin: 20px; padding: 20px; border: 1px solid #000;

  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.container.svg {
  background-image: url(https://svgshare.com/i/RWM.svg);
}
.container.img {
  background-image: url(https://images.pexels.com/photos/370799/pexels-photo-370799.jpeg?auto=compress&cs=tinysrgb&h=350);
}
<div class="container svg">
  some<br>content<br>makes<br>this<br>large
</div>
<div class="container img">
  some<br>content<br>makes<br>this<br>large
</div>


Solution

  • Okay, I just figured it out after reading a couple of other threads - including ones where it worked.

    The culprit was viewBox within the definition of the <svg>. When I removed it, the image scales as it should. And for safari I needed to add preserveAspectRatio="none".

    Before:

    <svg width="392px" height="499px" viewBox="0 0 392 499" ...
    

    After:

    <svg width="392px" height="499px" preserveAspectRatio="none" ...
    

    html, body {
      background-color: #ddd;
    }
    .container {
      margin: 20px; padding: 20px; border: 1px solid #000;
    
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }
    .container.svg {
      background-image: url(https://svgshare.com/i/RWM.svg);
    }
    .container.img {
      background-image: url(https://svgshare.com/i/RWv.svg);
    }
    <div class="container svg">
      some<br>content<br>makes<br>this<br>large
    </div>
    <div class="container img">
      some<br>content<br>makes<br>this<br>large
    </div>