我第一次使用 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
蓝色背景是 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>
注意事项:
- 使用此
preserveAspectRatio
属性最初由另一个答案提供 - 我忘记了用户,不过非常感谢他 - 它被删除了,在那个答案中属性是preserveAspectRatio="xMidYMid slice"
但不使用width="100%" height="100%"
,除了 CSS 中的那些不起作用,除了 [部分地,因为如果你将 View 调整得更大,蓝色背景将开始显示 ] 在 Chrome 中,如 @Paul LeBeau 中所述回答。这个jsFiddle Demo代表那个很好的答案。 -
none
不强制比例统一,它可能会挤压或拉伸(stretch)图像以使其适合,虽然它在 OP 情况下没有任何区别,如果保持宽高比是需要,然后是 the other 中的任何一个Min
,Mid
和Max
对于x
或y
可以使用但必须附上slice
只有而不是meet
.
关于html - 如何使 svg 图像适合父容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44011677/