11

Is there a way how to apply z-index on a SVG path?

I have simple SVG arrow:

<svg class="arrow">
  <path class="line" />
  <path class="endpoint"/>
</svg>

If I use css to chnge z-index of the whole .arrow everything works fine, but when I try to apply it only on .endpoint it doesn't work.

Is there some solution or workaround for this?

Thank you very much.

Aida_Aida
  • 541
  • 1
  • 3
  • 16
  • I believe everything will be relative to the svg canvas and not other dom elements. – agconti Nov 13 '13 at 16:23
  • possible duplicate of [How to use z-index in svg elements?](http://stackoverflow.com/questions/17786618/how-to-use-z-index-in-svg-elements) – givanse Feb 21 '15 at 03:16

3 Answers3

17

There's no z-index in SVG, it uses painters model. You'd have to remove the path from the DOM and re-add it before any elements that should be on top of it and after any elements that it should be on top of.

As you've discovered z-index only works on the complete <svg> content as the html renderer controls how that is positioned before handing off to the SVG renderer to draw the internal SVG contents.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
15

As an alternative, you can use "< use >"

Example:

<svg>
    <circle id="shape1" cx="20" cy="50" r="40" fill="yellow" />
    <rect id="shape2" x="4" y="20" width="200" height="50" fill="grey" />
    <circle id="shape3" cx="70" cy="70" r="50" fill="blue" />
    <use id="use" xlink:href="#shape2" />
</svg>

The shape2 layer will be the top most layer.

shibualexis
  • 4,534
  • 3
  • 20
  • 25
  • but you have 2 elements (#shape2 cloned!). what about 100 elements? try a look [here](https://stackoverflow.com/a/55526837/4935426) – tdjprog Apr 05 '19 at 00:59
-1

If you have a dire need to do it, you can define an explicit compositing order using alternate filter effects (as long as you don't need support in Firefox or IE.)

Michael Mullany
  • 30,283
  • 6
  • 81
  • 105
  • 3
    Could you expand on what you mean by "define an explicit compositing order using alternate filter effects " (a link or example would be great!). This could be useful for a project I'm working on - specifically, I'm trying to avoid flicker on a 3d-like carousel of SVG elements that contain clipped images. To get the z-stacking right, I have to re-order them, and this seems to cause the flicker as each image gets reloaded. – Sam Stainsby Dec 15 '13 at 01:39