Search code examples
htmlcsssvgrectangles

How to stretch all rectangles in SVG so they take all width


I have this 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>

Currently SVG takes the width of the parent container but rectangles stay the same size. I want them take all width and scale with window resize. How do I achieve this?


Solution

  • The key is to add the width and the x values as percentages.

    An example would be the following :

    <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>