Search code examples
htmlcsssvgsvg-animatesvg-filters

Hi guys, I need to deal with shadows in svg


This is a map of one area from Kazakhstan I need that when hovering, shadows appear at each city/element as in this picture: enter image description here

Here is actually the SVG code itself: CodePen link https://codepen.io/sTenzo/pen/JjNbvLm

I tried to apply CSS3 shadow properties but they don't work. Perhaps you need to create the same elements under the elements, but a little bigger and darker, this is already managed with "opacity" and "hover", but I have no idea how to do it. I will be glad for any help.


Solution

  • You could use the filter: drop-shadow() css property (which actually has its origins in SVG). Here's an updated codepen showing it in action (change is on line 20):

    https://codepen.io/maqam7/pen/KKmNBWj

    Note that one issue you will run into with using hover in this way is that child elements of <svg> unfortunately don't support z-index css properties as of this writing (so you can't set the :hover pseudo-class to have the highest z-index like you could with html elements). As-is, you're going to have some shapes having part or all of their shadows obscured by neighbors because of their order in the DOM.

    See: How to use z-index in svg elements?

    To mitigate this problem, you may need to use Javascript mouseover events to move the element being hovered to the end of the node list.


    [edit]

    Another way to solve the layering problem without having to use Javascript is to duplicate all the regions, make sure the duplicates come after the originals in the node list, and set the duplicates to be transparent by default.

    The bottom layer is always visible with the "idle" visual state, and the hover state is actually an entirely separate shape that only appears when hovered. Simple and straightforward, but the downside is that it doubles your svg markup (from ~92kb to ~184kb). Nevertheless, here's a working codepen with this solution:

    https://codepen.io/maqam7/pen/eYWBqEE

    Note that in this updated example, I appended all of the duplicated id attribute values with --interactive to make them unique and easily identifiable. Obviously, feel free to change any of those values. This is just a working proof of concept.

    [/edit]