gpt4 book ai didi

svg - 在另一个 SVG 元素中响应地居中 SVG 元素?

转载 作者:行者123 更新时间:2023-12-02 03:29:18 27 4
gpt4 key购买 nike

我正在尝试在 SVG 中做一些非常简单的事情:

  • 将整个视口(viewport)分成两个矩形
  • 每个矩形的宽度应为视口(viewport)宽度的 50%
  • 每个矩形的高度应为视口(viewport)高度的 100%
  • 在每个矩形的中心,绘制另一个 100px 宽和 40px 高的矩形
  • 每个“子”矩形的中心,由于没有更好的术语,应该与它们各自的“父”矩形的中心对齐——在任何视口(viewport)大小 .

  • 这是我想要实现的示例,但使用 <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/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com