【发布时间】:2017-09-16 06:19:05
【问题描述】:
我试图将一个大的 svg 放在一个容器 div 中,同时最大化 svg 的大小并保持纵横比。
由于某种原因,svg显示正确,但是width和height属性不正确,好像svg扩展成整个父级。
我怎样才能使 svg 具有正确的大小?
请,这应该只用 CSS 解决,不要用 javascript。
另外,请注意,如果我将 svg 替换为大图像,这将有效。
var info = document.getElementById('info');
var svg = document.getElementById('svg');
var box = svg.getBoundingClientRect();
info.textContent = 'the ratio is ' + (box.width / box.height) + ' instead of 2.5! The yellow square is not in the viewBox, so why does it show up?';
.container {
position: absolute;
top: 40px;
left: 40px;
right: 40px;
bottom: 40px;
}
.svg {
position: absolute;
max-height: 100%;
max-width: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: gray;
}
<div class="container">
<svg id="svg" class="svg" width="1000px" height="500px" viewBox="0 0 10 5">
<rect width="10" height="5" fill="black" />
<rect x="-2" y="2" width="1" height="1" fill="yellow" />
</svg>
</div>
<div id="info"/>
【问题讨论】:
-
相信你也想达到和
background-size: cover一样的效果。如果您不打算支持旧浏览器而只支持常绿浏览器,可以尝试object-fit: cover。 -
@Terry:不,我正在尝试进行对象匹配:包含。不知道这些东西应该如何工作。一旦我删除最大宽度或最大高度,svg 就会变得太大
-
@CBroe:不确定这有什么帮助,溢出没有任何作用,我认为这不是我遇到的问题。
-
那我想我不明白你到底遇到了什么问题......只有当你的 SVG 图像中有实际内容时,这些灰色部分才能被覆盖。如果容器不够高以显示整个图像...或 什么?
标签: javascript css svg css-position