SVG 图像未与 100vh 视口中的 'object-fit' 等价物对齐

SVG image not aligning to equivalent of 'object-fit' in 100vh viewport

我正在尝试让 SVG 图像等同于 100vh 全屏容器中的 object-fit。据我所知,我需要使用 preserveAspectRatio="xMidYMid slice" 属性并设置 width="100%" height="100%"

不过我似乎无法让它工作?当我玩弄它时,容器底部会显示一大块空白,或者当图像填充视口时,视口会变得比 100vh 大很多?

请注意,我不能使用 CSS 背景图像 属性,因为它是我正在构建的更广泛的 SVG/Javascript 动画的一部分。

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

有谁知道这里出了什么问题以及解决方案是什么?

提前感谢您的帮助/想法。

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

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

There are multiple sizing mechanisms at work; one for the <svg> element, one for the <image> element.

The one you set for the <svg> element is not really helpfull. The viewBox attribute fits a coordinate system of 100 by 100 user units inside the container. This coordinate system is then the viewport for sizing the <image> with an implicit preserveAspectRatio="xMidYMid meet". If you find that confusing: yes, that is the problem.

Instead, just size the <svg> element to fill the container. Remove the viewBox, set width and height to 100%. Without a viewBox, preserveAspectRatio also has no effect on the <svg> element.

Now, only the sizing mechanism for your image (fit the nimage into the 100% width and height of the viewport, as preserveAspectRatio describes), takes effect and works as you want it to.

General note: a JPG, as used in your <image>, has an inherent aspect ratio. Therefore preserveAspectRatio will always have an effect. A <svg> element has not. Only a viewBox has one. and is what the attribute works on.

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

#section-1, .background-clipped {
  width: 100%;
  height: 100%;
}
<section id="section-1">
<div class="background-clipped background-clipped-1">
    <svg id="home-image-1" width="100%" 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>