如何使< svg>元素是否扩展或收缩到其父容器? [英] How to make a <svg> element expand or contract to its parent container?
问题描述
目标是让< svg>元素展开为其父容器的大小,在这种情况下为< div>,无论容器有多大或小。
代码:
< style>
svg,#container {
height:100%;
width:100%;
}
< / style>
< div id =container>
< svg xmlns =http://www.w3.org/2000/svgversion =1.1>
< rect x =0y =0width =100height =100/>
< / svg>
< / div>
最常见的解决方案似乎是设置viewBox属性的< svg>元件。
viewBox =0 0 widthOfContainer heightOfContainer
然而,这似乎不适用于< svg>元件具有预定的宽度和/或高度。例如,< rect>元素,在上面的代码中,其宽度和高度显式设置。
所以显而易见的解决方案是使用%的宽度和%高度。但是这是否还要做呢?特别地,因为< img src = test.svg />工作正常和扩展/契约没有任何问题,显式设置< rect>高度和宽度。
如果像< rect>和像其他元素一样的元素必须以百分比形式定义其宽度和高度,Inkscape以设置它,使得具有< svg>
viewBox code>不是容器的高度,它是你的绘图的大小。将
viewBox
定义为宽度为100个单位,然后将您的 rect
定义为10个单位。之后,无论大小,你缩放SVG, rect
将是图像的宽度的10%。
The goal is to have the <svg> element expand to the size of its parent container, in this case a <div>, no matter how big or small that container may be.
The code:
<style>
svg, #container{
height: 100%;
width: 100%;
}
</style>
<div id="container">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" >
<rect x="0" y="0" width="100" height="100" />
</svg>
</div>
The most common solution to this problem seems to be setting the viewBox attribute on the <svg> element.
viewBox="0 0 widthOfContainer heightOfContainer"
However, this does not seem to work in cases where elements within the <svg> element have predefined widths and/or heights. For example, the <rect> element, in the above code, has its width and height explicitly set.
So the obvious solution is to use % widths and % heights on those elements as well. But does this even have to be done? Especially, since <img src=test.svg /> works fine and expands/contracts without any problems with explicitly set <rect> heights and widths.
If elements like <rect>, and other elements like it, have to have their widths and heights defined in percentages, is there a way in Inkscape to set it so that all elements with the <svg> document use percentage widths, heights, etc.. instead of fixed dimensions?
The viewBox
isn't the height of the container, it's the size of your drawing. Define your viewBox
to be 100 units in width, then define your rect
to be 10 units. After that, however large you scale the SVG, the rect
will be 10% the width of the image.
这篇关于如何使< svg>元素是否扩展或收缩到其父容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!