Repeat SVG pattern horizontally on a larger container

2.4k views Asked by At

I need to repeat an svg <pattern> on a horizontal <rect>.

I mean, the svg <rect> is larger that the pattern, so I need it to repeate horizontally on whatever space is left.

I want the main pattern to appear in the center, which is exactly what is happening now. I just need to make it repeat on both sides.

Right now, I can only get it to show once.

enter image description here

Note:

  • The pattern is the black triangle
  • The 1px dotted red border is from the svg element

.mySvg {
  width: 600px;
  height: 50px;
  border: 1px dotted red;
}
<svg class="mySvg">
  <defs>
    <pattern id="wave" viewBox="0,0,150,50" width="100%" height="100%">
      <path d="M 0 50 l 75 -50 l 75 50" stroke="black" stroke-width="2"/>
    </pattern>
  </defs>
  <rect x="0" y="0" width="100%" height="100%" fill="url(#wave)"/>
</svg>

How can I make the pattern repeat on the space that is left?

2

There are 2 answers

2
Temani Afif On

Use the SVG as background:

.box {
  height:50px;
  border:1px solid red;
  margin: 5px;
  background:
    url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 -2 150 52"><path d="M 0 50 l 75 -50 l 75 50" stroke="black" /></svg>') 
    center/auto 100%;
}
<div class="box"></div>

<div class="box" style="height:100px;"></div>

2
enxaneta On

In your code the pattern is having a width of 100%. It can't repeat. I gave the pattern a width of 25%. Also to make it fall in the middle I'm offsetting the pattern a 12.5% (25/2) x="12.5%"

.mySvg {
  width: 600px;
  height: 50px;
  border: 1px dotted red;
}
<svg class="mySvg" viewBox="0 0 600 50">
  <defs>
    <pattern id="wave" x="12.5%" y="0" width="25%" height="100%">
      <path d="M 0 50 l 75 -50 l 75 50" stroke="black" stroke-width="2"/>
    </pattern>
  </defs>
  <rect x="0" y="0" width="100%" height="100%" fill="url(#wave)"/>
</svg>