BigMac66
BigMac66

Reputation: 1538

Change SVG fill of only the element being hovered over

For some reason I can not get my hover to work properly. It changes the fill of every item that has the same class and I am not sure why. I am using DEFS and USE which is different from all the examples I have seen that work the way I want.

The included code has been simplified to two rectangles and I only want the one hovered over to change color.

CSS

rect
{
    stroke-width : 3;
    stroke : black;
    width : 300;
    height : 100;
    rx : 15;
    ry : 15;
}

text
{
    stroke : black;
    fill : gold;
    text-anchor : middle;
    pointer-events: none;
}

.client
{
    fill : lightsalmon;
}

.client:hover
{
    fill : green;
}

HTML

<!DOCTYPE HTML>
<HTML>
    <HEAD>
        <LINK rel="stylesheet" type="text/css" href="Test.css">
    </HEAD>
    <BODY>
        <DIV id="svgDiv">
            <SVG id="svgDoc" width="100%" viewBox="0, 0, 1500, 1000">
                <DEFS>
                    <G id="table">
                        <RECT width="300" height="90" />
                    </G>
                </DEFS>
                
                <G id="clientTables" transform="translate(0, 250) scale(0.5 0.5)" class="client">
                    <G id="TCLNT" transform="translate(500, 250)">
                        <USE xlink:href="#table" />
                        <TEXT x="150" y="50">TEST_CLNT</TEXT>
                    </G>
                    <G id="TCPHN" transform="translate(50, 50)">
                        <USE xlink:href="#table" />
                        <TEXT x="150" y="50">TEST_CLNT_PHN</TEXT>
                    </G>
                </G>
            </SVG>
        </DIV>
    </BODY>
</HTML>

Upvotes: 1

Views: 35

Answers (1)

s.kuznetsov
s.kuznetsov

Reputation: 15213

The .client class is a wrapper for two elements. For this reason, you get targeting both elements when hovering.

It is necessary to connect the <g> tag to the :hover selector. Do it like this:

.client g:hover {
  fill : green;
}

Upvotes: 2

Related Questions