1

I want to draw an arrow over a single active svg rect using css. my svg looks similar to this:

<svg>
   <rect width="16" height="41" transform="translate(781.5 384) rotate(90)" fill="#f8ce8b"/>
   <rect class="active" width="16" height="41" transform="translate(781.5 384) rotate(90)" fill="#f8ce8b"/>
</svg>

Actual svg link: https://terrasanta.com.au/map.html

css code:

rect.active::after{
  content: "";
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 100px 100px 100px;
  border-color: transparent transparent #007bff transparent;
}

But its not working. Can anyone please tell how I can do this. .

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
Hamza.am.i
  • 123
  • 1
  • 10
  • Please read this answer: [CSS :before on inline SVG](https://stackoverflow.com/questions/24026458/css-before-on-inline-svg#24026800) – enxaneta Jun 08 '19 at 08:27
  • Is there any other way that i can place an element in a svg in a particular position dynamically – Hamza.am.i Jun 08 '19 at 09:08

1 Answers1

1

As I've commented: this answer explains why you can't: CSS :before on inline SVG

inline SVG is treated as an image, and images are replaced elements which are not allowed to have generated content.

The OP is commenting:

Is there any other way that i can place an element in a svg in a particular position dynamically

This is how I would do it:

Please observe that I've wrapped the rects in a group <g>

For each rect in the document I check if the rect has a class "active" and if it does I add a new svg element.

const SVG_NS = 'http://www.w3.org/2000/svg';
//all the rects
let rects = document.querySelectorAll("rect");

// for each rect 
rects.forEach(r=>{
  let bb = r.parentNode.getBBox();
  //check if the rect has a class "active"
  if(r.classList.contains("active")){
      // and add a new element - in this case a circle
      drawSVGelmt({cx:bb.x,cy:bb.y,r:10,}, "circle", r.parentNode)
  }
})

// a function used to create a new svg element
function drawSVGelmt(o, tag, parent) {

let elmt = document.createElementNS(SVG_NS, tag);
  for (var name in o) {
    if (o.hasOwnProperty(name)) {
      elmt.setAttributeNS(null, name, o[name]);
    }
  }
  parent.appendChild(elmt);
  return elmt;
}
svg{border:1px solid}
circle{fill:red}
<svg viewBox="730 374 61 36" width="100">
  <g>
   <rect width="16" height="41" transform="translate(781.5 384) rotate(90)" fill="#f8ce8b"/>
  </g>
  <g>
   <rect class="active" width="16" height="41" transform="translate(781.5 384) rotate(90)" fill="#f8ce8b"/>
  </g>
</svg>
enxaneta
  • 31,608
  • 5
  • 29
  • 42