在另一个SVG元素中响应中心SVG元素?

时间:2015-01-21 05:10:54

标签: svg responsive-design fullscreen

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

  1. 将整个视口划分为两个矩形
  2. 每个矩形的宽度应为视口宽度的50%
  3. 每个矩形的高度应为视口高度的100%
  4. 在每个矩形的中心,绘制另一个100px宽和40px高的矩形
  5. 这些"孩子的中心"由于缺乏更好的术语,矩形应该与它们各自的父母的中心对齐。矩形 - 任何视口大小
  6. 以下是我想要实现的一个示例,但使用<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形状?

1 个答案:

答案 0 :(得分:1)

事实证明,响应式SVG设计的秘诀在于让屏幕上的每个对象都是自己的<svg>元素。换句话说,使用<svg>作为组标记。

为什么呢?因为可以使用百分比来定位<svg>元素。

要将<svg>放在其中心而不是左上角,请使用其transform="translate(dx,dy)"属性。

在我们的示例中,放置文本和&#34; child&#34;在他们自己的<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中测试)

相关问题