2017-09-15 98 views
-1

中心大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"/>

+0

https://css-tricks.com/scale-svg/ – CBroe

+0

我相信你想达到为'背景大小相同的效果:cover'。如果你不支持旧的浏览器,只有不断绿色的计划,你可以试试['对象的配合:cover'(https://developer.mozilla.org/en-US/docs/Web/CSS /对象配合)。 – Terry

+0

@Terry:不,我正在尝试做对象拟合:包含。不知道这些东西应该如何工作。只要我删除最大宽度或最大高度,svg就会变得太大 –

回答

1

从某种意义上说,你已经SVG是配件在其容器,你希望它的方式。实际上,您定义的大多数CSS都可以保留。 SVG元素应该使用width: 100%, height: 100%来定义,因此<svg>元素本身的大小与其容器相同。然后,由viewBox所限定的区域被根据属性preserveAspectRatio="xMidYMid meet"渲染到这个。 (隐式使用,这是它的默认值):保留纵横比,放在里面的最大尺寸,位于中间。

与黄色矩形问题就出现了,只是因为内容是在,而不是视框的边缘裁剪。因此,在SVG中定义的内容,但在viewBox外部仍可见。

(有最初是为了支持<svg>元素上的clip样式属性的想法,但它的概念是如此令人费解的即是不可用的,现在已经过时了。)

最好的解决办法,现在是将<svg>元素与另一个<svg>包装在一起。内层获取宽度和高度的绝对值,外层获取与viewBox和width: 100%, height: 100%相同的值。如你所见,内部svg在其边缘剪辑内容,而外部svg将内容嵌入到容器中。

请注意,您无法在内部svg上定义CSS background-color。这仅仅是为HTML定义的,仅在外部工作,因为它是HTML元素的直接子元素。如果您想要彩色背景,请使用适当的fill定义覆盖viewBox区域的矩形。

.container { 
 
    position: absolute; 
 
    top: 40px; 
 
    left: 40px; 
 
    right: 40px; 
 
    bottom: 40px; 
 
} 
 

 
#svg1 { 
 
    height: 100%; 
 
    width: 100%; 
 
    background-color: gray; /* clipped at the borders of the container! */ 
 
}
<div class="container"> 
 
    <svg id="svg1" class="svg" viewBox="0 0 10 5"> 
 
    <svg id="svg2" width="10" height="5"> 
 
     <rect width="10" height="5" fill="black" /> <!--this is your background--> 
 
     <rect x="-2" y="2" width="1" height="1" fill="yellow" /> 
 
     <ellipse cx="5" cy="2.5" rx="6" ry="3" 
 
       fill="none" stroke="blue" stroke-width="0.2" /> 
 
    </svg> 
 
    </svg> 
 
</div> 
 
<div id="info"/>