Search code examples
htmlcsssvgaspect-ratiobackground-position

Equivalent to background position percentage (%) in SVG


I have an SVG image that has the equivalent of background-size: cover; assigned to it using preserveAspectRatio="xMidYMid slice".

However on phone devices less than 737px I'd like to move this image to the left within its container. If was was using the CSS background property I would just do background-position: 85%; or similar.

Is there an equivalent way of doing this with SVG images?

Codepen: https://codepen.io/emilychews/pen/Zqragv

Many thanks in advance for any help.

body {
  margin: 0;
  padding: 0;
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
}

#section-1, .home-image-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.home-image, .home-image-wrapper {
  position: absolute;
  right: 0;
}

#home-image-1 {right: 0%}
<section id="section-1">
  
  <div class="home-image-wrapper">
    
    <svg class="home-image" id="home-image-1" width="60%" height="100%">
      <image xlink:href="https://i.postimg.cc/9XdQKYF1/dimon-blr-309444-unsplash.jpg" x="0" y="0" width="100%" height="100%" preserveAspectRatio="xMidYMid slice"/>
    </svg>
    
  </div>
  
</section>


Solution

  • Setting position on svg elements

    If you just want to change the svg element on a container (assuming <g> element). You can apply a simple transform on any element:

    Example:

    <svg viewBox="0 0 100 100" width="300px">
      <!--black rect-->
      <g>
        <rect x="0" y="0" width="20" height="20" />
      </g>
      <!--blue rect-->
      <g transform="translate(20)" fill="#08a">
        <rect x="0" y="20" width="20" height="20" />
      </g>
    </svg>