Home > front end >  Create a horizontal linear gradient across an SVG group and not on the individual parts of the group
Create a horizontal linear gradient across an SVG group and not on the individual parts of the group

Time:06-02

Is it possible to create a horizontal gradient that applies to the entire group instead of each individual piece? I am trying to build a progress bar composed of multiple rectangles with space in between (see snippet) but it doesn't seem possible unless I create logic for each individual which is not ideal

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3/org/1999/xlink" viewBox="0 0 225 38" preserveAspectRatio="none" width="100%" height="100%">
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100sv%" y2="0%">
      <stop offset="50%" stop-color="green" />
      <stop offset="50%" stop-color="black" />
    </linearGradient>
  </defs>

  <defs>
    <linearGradient id="grad2" x1="0" x2="0" y1="0" y2="1">
      <stop offset="50%" stop-color="green"/>
      <stop offset="50%" stop-color="black" />
    </linearGradient>
  </defs>

  <g fill="url(#grad1)">
    <rect x="10" y="1" width="6" height="15" />
    <rect x="20" y="1" width="6" height="15" />
    <rect x="30" y="1" width="6" height="15" />
    <rect x="40" y="1" width="6" height="15" />
    <rect x="50" y="1" width="6" height="15" />
  </g>
</svg>

<p>desired look</p>

<div style="display: flex; flex-direction: row"> 
  <div style="width: 6px; height: 15px; margin-right: 5px; background-color: green"></div>
  <div style="width: 6px; height: 15px; margin-right: 5px; background-color: green"></div>
  <div style="width: 6px; height: 15px; margin-right: 5px; background-color: green"></div>
  <div style="width: 6px; height: 15px; margin-right: 5px; background-color: black"></div>
    <div style="width: 6px; height: 15px; margin-right: 5px; background-color: black"></div>
</div>

CodePudding user response:

Set attribute gradientUnits="userSpaceOnUse" and use the coordinate of the leftmost side of your grafics for x1 (x1="10") resp. the rightmost for x2 (x2="56").

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3/org/1999/xlink" viewBox="0 0 225 38" preserveAspectRatio="none" width="100%" height="100%">
  <defs>
    <linearGradient gradientUnits="userSpaceOnUse" id="grad1"
                    x1="10" y1="0" x2="56" y2="0">
      <stop offset="50%" stop-color="green" />
      <stop offset="50%" stop-color="black" />
    </linearGradient>
  </defs>

  <g fill="url(#grad1)">
    <rect x="10" y="1" width="6" height="15" />
    <rect x="20" y="1" width="6" height="15" />
    <rect x="30" y="1" width="6" height="15" />
    <rect x="40" y="1" width="6" height="15" />
    <rect x="50" y="1" width="6" height="15" />
  </g>
</svg>

  •  Tags:  
  • svg
  • Related