我想实现几个 SVG 的布局,如下图所示。
灰色框是包含其他元素的顶级 SVG。宽度和高度已知。
橙色框包含红色框,并且需要彼此保持相同的距离。类似于 justify-content: space-around 对齐元素的方式。
红色框也以相同的方式保持距离(但垂直)。
我一直在尝试使用 transform-origin
调整位置,但似乎不起作用。相反,偏移量始终从每个元素的左上角计算,这会将元素推出 View 之外。这是一个非常基本的片段,但遗憾的是这就是我所拥有的一切。
<svg width="400" height="400" style="background:#ccc;">
<g transform="translate(10, 10)">
<svg width="50" height="50">
<rect width="50" height="50" fill="red" />
</svg>
<svg width="50" height="50">
<rect width="50" height="50" fill="red" />
</svg>
<svg width="50" height="50">
<rect width="50" height="50" fill="red" />
</svg>
</g>
<g transform="translate(200, 10)">
<svg width="50" height="50">
<rect width="50" height="50" fill="red" />
</svg>
<svg width="50" height="50">
<rect width="50" height="50" fill="red" />
</svg>
<svg width="50" height="50">
<rect width="50" height="50" fill="red" />
</svg>
</g>
<g transform="translate(360, 10)">
<svg width="50" height="50">
<rect width="50" height="50" fill="red" />
</svg>
<svg width="50" height="50">
<rect width="50" height="50" fill="red" />
</svg>
<svg width="50" height="50">
<rect width="50" height="50" fill="red" />
</svg>
</g>
</svg>
有没有办法在不知道红色框大小的情况下以这种方式对齐这些容器? 我最终得到的每个解决方案都使用一些计算,其中我需要减去红色框的宽度和高度的一半。
最佳答案
正如评论中指出的@enxaneta:
Instead of using all those nested svg elements you can put a rect in the defs. the rect would be centered around the point 0,0
在 SVG 中,元素位置相对于 Canvas 的左上角。
如果指定相同的x=40
多个矩形的坐标,然后它们将垂直对齐。
为了不为每个矩形写入其坐标值以及 width
的值和height
,您需要在 <defs>
中放置一个实例部分,然后使用 <use>
克隆它标签。
在这种情况下,您需要指定坐标 x
, y
对于每个副本:
<use xlink:href="#rect" x="40" y="62.5" />
要获得三列,您需要将一列包装在 <g>
中组标签并使用 <use>
克隆它
<use xlink:href="#column" x="150" y="0" />
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="450" height="400" viewBox="0 0 450 400" style="background:#ccc;">
<defs>
<rect id="rect" width="50" height="50" fill="red" x="0" y="0" />
</defs>
<g id="column" >
<rect x="30" y="0" width="70" height="400" fill="#C89F33" />
<use xlink:href="#rect" x="40" y="62.5" />
<use xlink:href="#rect" x="40" y="175" />
<use xlink:href="#rect" x="40" y="287.5" />
</g>
<use xlink:href="#column" x="150" y="0" />
<use xlink:href="#column" x="300" y="0" />
</svg>
关于html - 嵌套 SVG 的对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70801535/