简体   繁体   中英

resize an SVG background image proportionally

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM