html - 如何使 svg 图像适合父容器

标签 html css svg

我第一次使用 svg <image>标签。我使用此标签是为了在图片上应用灰色滤镜(感谢 IE)。

这是我的 HTML:

<div class="container">
  <div class="item">
    <svg version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
        <image  xlink:href="https://dummyimage.com/400x400/000/00ffd5.png" />
    </svg>
  </div>
</div> 

还有 scss:

.item {
  position: relative;
  width: 20%;
  height: 220px;

  background-color: blue;
}

svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

  image {
    width: 100%;
    height: 100%;
  }
}

我想让图像适应父容器。像 background: cover in css 之类的东西。有人有想法吗?

您可以在以下位置查看:https://codepen.io/seabon/pen/QvBBrd

enter image description here

蓝色背景是 div.item

最佳答案

已更新

  • 添加width="100%"height="100%"属性。
  • 添加 preserveAspectRatio 1 的值为 none 2

    none do not force uniform scaling. Scale the graphic content of the given element non-uniformly if necessary such that the element's bounding box exactly matches the viewport rectangle.
    Note: if <align> is none, then the optional <meetOrSlice> value is ignored.

jsFiddle - 在 Chrome、FF 和 IE11 上测试

.item { position: relative; width: 20%; height: 220px; background-color: blue; }
svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
<div class="item">
  <svg id="theSVG" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
      <image width="100%" height="100%" xlink:href="//dummyimage.com/400x400/000/00ffd5.png" preserveAspectRatio="none" />
    </svg>
</div>


注意事项:

  1. 使用此 preserveAspectRatio属性最初由另一个答案提供 - 我忘记了用户,不过非常感谢他 - 它被删除了,在那个答案中属性是 preserveAspectRatio="xMidYMid slice"但不使用 width="100%" height="100%" ,除了 CSS 中的那些不起作用,除了 [部分地,因为如果你将 View 调整得更大,蓝色背景将开始显示 ] 在 Chrome 中,如 @Paul LeBeau 中所述回答。这个jsFiddle Demo代表那个很好的答案。
  2. none 强制比例统一,它可能会挤压或拉伸(stretch)图像以使其适合,虽然它在 OP 情况下没有任何区别,如果保持宽高比是需要,然后是 the other 中的任何一个Min , MidMax对于 xy可以使用但必须附上slice只有而不是 meet .

关于html - 如何使 svg 图像适合父容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44011677/

相关文章:

angularjs - 当 ng-model 为空时如何在 md-input-container 上有一个 float 标签

javascript - 带有复选框 hack 的下拉列表 - 如何在不选择选项的情况下首次点击打开菜单?

jquery - Bootstrap - 将侧边导航扩展到页面底部。高度 100%

html - 有没有办法在 CSS 中设置默认边框颜色/大小?

javascript - 简单问题 : Do I need to specify width, "image"预加载图片时的高度?

html - 将 SVG 嵌入 HTML(特定于 Opera)

svg - svg 中的多行文本

javascript - 避免多次动态报价 onclick

html - 如何按比例将图像缩放到最大宽度?

c# - 使用 c# 和 xaml 在 Metro App 中显示 svg