skip to Main Content

All,

I’m pretty new to using SVGs, and I’m hoping someone here can explain to me how to target a particular element of my SVG with CSS?

What I’m trying to do is put together a country map where specific areas will appear darker when the user hovers over them. The map was made in layers in Photoshop, then imported in Illustrator and exported as a SVG file. So far, so good. But I’m running into trouble when I try to style their individual parts (which Illustrator put in “g” IDs and tags).

The code looks like this:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 1762 2043" style="enable-background:new 0 0 1762 2043;" xml:space="preserve" xmlns:xml="http://www.w3.org/XML/1998/namespace">

<g id="Area1">

        <image style="overflow:visible;" width="378" height="272" id="Area1" xlink:href=".../.../121F7A955DACD041.png" transform="matrix(1 0 0 1 657 912)">
    </image>
</g>

Followed by an “Area2”, “Area3”, etc.

Now I figured if I simply used “Area1:hover” in my stylesheet, it would work — but it doesn’t.

Oddly enough, when I set “display: none” for the same ID in my CSS, it DOES hide the area. So why won’t the hover attribute work?

2

Answers


  1. The <g> element defines a group of SVG elements. It doesn’t actually take up any space in the rendered SVG image. So there is nothing for you to :hover over in order to activate this rule in your stylesheet.

    You can fix this by setting :hover rules for the group’s child elements, or by adding a child selector to the CSS rule, like #Area1 > *:hover, for example.

    Here’s a simple example (JSFiddle link)

    CSS:

    #a1 > *:hover {
        fill:#fc0;
    }
    

    SVG:

    <svg viewBox="0 0 200 200">
        <g id="a1" style="fill:#e82">
            <path d="M50,50v100h100v-100z" />
        </g>
    </svg>
    

    Update: Creating SVG maps with :hover style attributes

    If you try to create an SVG map from multiple overlapping <image> elements, you’re going to have problems in the overlapping parts because the :hover style is only applied to the topmost element, even if it only contains transparent pixels.

    To fix this, you will have to apply an SVG clipping mask to each section of the map. Alternatively, you could create the map entirely from SVG elements. Here’s an example of the latter approach.

    Login or Signup to reply.
  2. I think your problem is that your group id (g tag) is the same id of your image element

    <image overflow="visible" width="209" id="Area1" height="248" xlink:href="//www.elige-argentina.com/assets/img/mapa-argentina.png"  transform="matrix(1 0 0 1 612.6923 23.6923)">
    </image>
    

    Working Fiddle: http://jsfiddle.net/b2f2jx0f/3/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search