中心大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就會變得太大 –