相当于SVG中的背景位置百分比(%)

Equivalent to background position percentage (%) in SVG

我有一个 SVG 图像,它使用 preserveAspectRatio="xMidYMid slice".

分配给它等效于 background-size: cover;

但是在 phone 小于 737px 的设备上,我想将此图像移动到其容器内的左侧。如果是使用 CSS background 属性 我会做 background-position: 85%; 或类似的。

是否有对 SVG 图像执行此操作的等效方法?

代码笔:https://codepen.io/emilychews/pen/Zqragv

非常感谢您的帮助。

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>

在 SVG 中,您可以设置 viewBox 属性。这定义了 SVG 可见部分的 x、y、宽度和高度。假设您的 jpg 图片的宽度为 200,高度为 100。在这种情况下,您将 viewBox="0 0 200 100" 默认设置为 <svg> 元素。在 phone 设备上,您可以将 viewBox 值更改为类似 50 0 100 100 的值,这样只会显示图像中间的 100 个像素。

您可以在此处找到有关 viewBox 属性的更多信息:http://jonibologna.com/svg-viewbox-and-viewport/

在 svg 元素上设置位置

如果您只想更改容器上的 svg 元素(假设为 元素)。 您可以对任何元素应用简单的转换:

示例:

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