2

I want to set an SVG as a background image with a height of 100px and the width set based on the image's original proportions (to avoid distortion). The XML of the SVG is

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   viewBox="0 0 600.09332 291.44"
   height="291.44"
   width="600.09332"
   xml:space="preserve"
   id="svg2"
   version="1.1">
  <!-- other markup omitted -->
</svg>

The CSS I'm using is

.image {
  display: block;
  height: 100px;
  width: auto;
  background-image: url(../images/header_logo.svg);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  background-color: transparent;
}

The image is not shown at all when I use width: auto. If I change this to width: 100px, the image is displayed, but the width/height proportions are distorted.

Dónal
  • 185,044
  • 174
  • 569
  • 824
  • If your _.image_ block is empty and its _display_ property is _block_ it will fit its parent element, not background image. _.image_ block is unaware of background sizes. Use _img_ tag, or set _width_ and _height_ proportionally. In your case `width: 206px;` – Igor Melekhov May 16 '19 at 13:35
  • Does this answer your question? [Resizing SVG in html?](https://stackoverflow.com/questions/3120739/resizing-svg-in-html) – Kavian Rabbani Jul 28 '20 at 09:35

1 Answers1

-3

Use an inline image for the background instead so it maintains the proportions correctly: https://jsfiddle.net/5cxr18jf/

<div class="wrapper">
   <h1>Other content</h1>
   <img class="background" src="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/compass.svg">
</div>

.wrapper {
  width: 500px;
  height: 500px;
  background: #ddd;
  position: relative;
}

.background {
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
}
Alex
  • 2,651
  • 2
  • 25
  • 45