我在转换内联SVG到divs中包装时遇到了问题。我以前使用过嵌套SVG,现在我被告知必须使用内联SVG的嵌套DIV。
基本上,我需要将SVG的大小调整到“container”--“container”的大小调整到浏览器窗口。
在我尝试整个div之前,有一个工作的例子:
仅SVG示例-运行良好
<html>
<body>
<svg id="container" style="position:relative;border:dashed;width:100%;height:100%;" viewBox="0 0 1000 500">
<svg id="background" name="Box" x="0" y="0">
<rect width="1000" height="500" stroke="lime" fill="blue" stroke-width="10" />
<svg id="shape" name="Triangle" x="275" y="50" fill="red" stroke="yellow" stroke-width="3">
<path d="M0,378L185,0L371,378Z" />
</svg>
</svg>
</svg>
</body>
</html>
null
但是当我尝试将div包装在它们周围时,无论我尝试了什么,它都与我的viewBox保持相同的大小。我在SO和其他地方查了很多这方面的资料,似乎没有什么工作:填充技巧,100VW,宽度,高度,等等。
以下是我最新尝试的:
SVG包装在DIV中示例-行为不相同
<html>
<body>
<div id="container" style="position:relative;border:dashed;width:100%;height:0;margin:5px">
<div id="background" style="position:absolute;left:0px;top:0px;width:1000px;height:500px;">
<svg name="Box" viewBox="0 0 1000 500">
<rect width="1000" height="500" stroke="lime" fill="blue" stroke-width="10" />
</svg>
<div id="shape" style="position:absolute;left:275px;top:50px;width:371px;height:378px;">
<svg name="Triangle" viewBox="0 0 371 378" fill="red" stroke="yellow" stroke-width="3">
<path d="M0,378L185,0L371,378Z" />
</svg>
</div>
</div>
</div>
</body>
</html>
null
我把一个“边框:虚线;在第一个div中,只是为了确保它是用browswer窗口调整大小的。只是div里面的一切都没有改变。
关于如何使“包装在DIV中”策略与“纯SVG”策略相匹配,有什么建议吗?
更清晰:我想我说的是“背景”形状需要1000W x 500h,相对于“容器”大小。任何一个它的孩子需要绝对定位在1000W500H内,并相对于它。“容器”大小是可用空间。因此,如果浏览器窗口是3000W x 2000H,那么技术上“背景”形状应该是3000W x 1500H(并且子形状也相应地调整大小--但是相对于1000W x 500H保持在它们原来的相对位置)。如果窗口800 w乘以600 h,则“背景”和子形状相对收缩以适应该窗口。就像SVG示例一样。
以上面的SVG示例为例,将其保存为html文件,在本地启动并上下调整浏览器大小,可能会有帮助。这就是我要找的帮助,但divs似乎不知道如何处理这件事。
在DIV元素上没有SVG的viewBox属性的真正等价物。最接近的一个会改变规模。因此,如果您给您的div容器一个特定的像素大小,而不调整resize,您将会在一定程度上覆盖viewbox的计算。
这就是说,如果您的div容器与窗口一起调整大小,那么它可以工作。同样,使用最小javascript,您可以得到与ViewBox相同的结果。
对于仅css的解决方案,您可以定义您的div容器,使它们的大小达到窗口的100%。SVG viewbox仍然在进行计算。您需要定义一个preserveAspectRatio以具有与SVG示例相同的行为。像这样:
null
html, body {
width: 100%;
height: 100%;
padding: 0px;
margin:0px;
}
* {
box-sizing: border-box;
}
<div id="container" style="position:relative;border:dashed;width:100%;height:100%;">
<svg name="Box" style="position:relative;width:100%;height:100%;" viewBox="0 0 1000 500" preserveAspectRatio="xMinYMin">
<rect width="100%" height="100%" stroke="lime" fill="blue" stroke-width="10" />
</svg>
<div id="shape" style="position:absolute;left:0px;top:0px;height:100%;width:100%;">
<svg style="position:relative;width:100%;height:100%;" viewBox="0 0 1000 500" preserveAspectRatio="xMinYMin">
<svg id="shape" name="Triangle" x="275" y="50" width="371" height="378" fill="red" stroke="yellow" stroke-width="3">
<path d="M0,378L185,0L371,378Z" />
</svg>
</svg>
</div>
</div>