【问题标题】:How to stretch all rectangles in SVG so they take all width如何在 SVG 中拉伸所有矩形,使其占据所有宽度
【发布时间】:2020-06-18 05:59:38
【问题描述】:

我有这个 SVG:

<svg width="100%" height="40" viewBox="0 0 371 40" fill="none" xmlns="http://www.w3.org/2000/svg">
    <rect x="57"  y="1" width="45" height="15" fill="#e1d6f2"/>
    <rect x="103" y="1" width="45" height="15" fill="#c1b0e2"/>
    <rect x="149" y="1" width="45" height="15" fill="#9b80ce"/>
    <rect x="195" y="1" width="45" height="15" fill="#6d4cbf"/>
    <rect x="241" y="1" width="45" height="15" fill="#4d2c7a"/>
    <text x="57" y="38" text-anchor="middle" fill="#000">0</text>
    <text x="102" y="38" text-anchor="middle" fill="#000">20</text>
    <text x="147" y="38" text-anchor="middle" fill="#000">40</text>
    <text x="192" y="38" text-anchor="middle" fill="#000">60</text>
    <text x="237" y="38" text-anchor="middle" fill="#000">80</text>
    <text x="290" y="38" text-anchor="middle" fill="#000">100%</text>
</svg>

目前 SVG 采用父容器的宽度,但矩形保持相同大小。我希望它们通过调整窗口大小来获取所有宽度和比例。我如何做到这一点?

【问题讨论】:

    标签: html css svg rectangles


    【解决方案1】:

    关键是将宽度和x 值添加为百分比。

    一个例子如下:

    <svg width="100%" height="40" xmlns="http://www.w3.org/2000/svg">
      <rect width="25%" height="15" fill="#e1d6f2" />
      <rect width="25%" height="15" fill="#c1b0e2" x="20%" />
      <rect width="25%" height="15" fill="#9b80ce" x="40%"/>
      <rect width="25%" height="15" fill="#6d4cbf" x="60%"/>
      <rect width="25%" height="15" fill="#4d2c7a" x="80%"/>
      <text x="3%" y="38" text-anchor="middle" fill="#000">0</text>
      <text x="20%" y="38" text-anchor="middle" fill="#000">20</text>
      <text x="40%" y="38" text-anchor="middle" fill="#000">40</text>
      <text x="60%" y="38" text-anchor="middle" fill="#000">60</text>
      <text x="80%" y="38" text-anchor="middle" fill="#000">80</text>
      <text x="96%" y="38" text-anchor="middle" fill="#000">100%</text>
    </svg>

    【讨论】:

    • 太棒了!正是我想要的!唯一更重要的是:您认为仍然可以在这个比例的边缘上对齐 0% 和 100% 吗?就像我在示例中那样。
    • @OlgaB 如果你这样做,那么它们将出现在窗口之外,因为矩形占据了 100% 的宽度:jsfiddle.net/wf31ky7t
    • 您可以尝试继续减少直到获得所需的结果(jsfiddle.net/x98vn12g),但您在 OP 中要求全宽,所以我就是这样做的 :-) 您需要任何代码解释吗?
    • 是的,我打算建议我可以继续减少这个。 :) 再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 2022-11-20
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多