中心大SVG我想在一个容器div来中心的大SVG同时最大化SVG的大小并保持纵横比。集装箱
由于某些原因,svg显示正确,但宽度和高度属性不正确,就好像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"/>
https://css-tricks.com/scale-svg/ – CBroe
我相信你想达到为'背景大小相同的效果:cover'。如果你不支持旧的浏览器,只有不断绿色的计划,你可以试试['对象的配合:cover'(https://developer.mozilla.org/en-US/docs/Web/CSS /对象配合)。 – Terry
@Terry:不,我正在尝试做对象拟合:包含。不知道这些东西应该如何工作。只要我删除最大宽度或最大高度,svg就会变得太大 –