pjk_ok
pjk_ok

Reputation: 967

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>

Upvotes: 1

Views: 360

Answers (2)

Persijn
Persijn

Reputation: 15000

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>

Upvotes: 1

Waruyama
Waruyama

Reputation: 3533

In SVG you can set the viewBox attribute. This defines the x, y, width and height of the visible part of the SVG. Let's say your jpg image has a width of 200 and a height of 100. In this case you set viewBox="0 0 200 100" by default to the <svg> element. On phone devices you can change the the viewBox value to something like 50 0 100 100, which would only display the middle 100 pixels of the image.

You can find more on the viewBox attribute here: http://jonibologna.com/svg-viewbox-and-viewport/

Upvotes: 0

Related Questions