我正在尝试在 SVG 中做一些非常简单的事情:
这是我想要实现的示例,但使用
<text>
元素而不是 <rect>
要素:<svg version="1.1" width="100%" height="100%">
<svg x="0" y="0" width="50%" height="100%" overflow="visible">
<rect x="0" y="0" width="100%" height="100%" fill="#363636"></rect>
<text x="50%" y="50%" text-anchor="middle" text-color="#393939">Sign In</text>
</svg>
<svg x="50%" y="0" width="50%" height="100%" overflow="visible">
<rect x="0" y="0" width="100%" height="100%" fill="#999999"></rect>
<text x="50%" y="50%" text-anchor="middle">Sign Up</text>
</svg>
</svg>
就此而言,我如何使用矩形或任何 SVG 形状来做到这一点?
最佳答案
事实证明,响应式 SVG 设计的秘诀是让屏幕上的每个对象都有自己的 <svg>
元素。换句话说,使用 <svg>
作为组标签。
为什么?因为<svg>
元素可以使用百分比定位。
定位 <svg>
在它的中心而不是它的左上角,使用它的transform="translate(dx,dy)"
属性(property)。
在我们的示例中,将文本和“子”矩形放在它们自己的 <svg>
中父级,然后对其进行转换,以实现所需的效果:
<svg version="1.1" width="100%" height="100%">
<!-- Left Column -->
<svg x="0" y="0" width="50%" height="100%" overflow="visible">
<!-- "Parent" Rectangle -->
<rect x="0" y="0" width="100%" height="100%" fill="#363636"></rect>
<!-- "Child" Rectangle with Text -->
<svg x="50%" y="50%" width="116" height="40" overflow="visible">
<rect x="0" y="0" width="100%" height="100%" rx="20" ry="20" fill="#FFFFFF" transform="translate(-58, -25)"></rect>
<text x="0" y="0" text-color="#393939" transform="translate(-29, 0)">Sign Up</text>
</svg>
</svg>
<!-- Right Column -->
<svg x="50%" y="0" width="50%" height="100%" overflow="visible">
<!-- "Parent" Rectangle -->
<rect x="0" y="0" width="100%" height="100%" fill="#999999"></rect>
<!-- "Child" Rectangle with Text -->
<svg x="50%" y="50%" width="100" height="40" overflow="visible">
<rect x="0" y="0" width="100%" height="100%" rx="20" ry="20" fill="#FFFFFF" transform="translate(-50, -25)"></rect>
<text x="0" y="0" text-color="#393939" transform="translate(-25, 0)">Sign In</text>
</svg>
</svg>
</svg>
(在 Mac OS X Chrome 39.0 和 iOS 8.1.2 Safari 中测试)
关于svg - 在另一个 SVG 元素中响应地居中 SVG 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28060051/