Search code examples
csssvghoverrect

SVG element hovering to cause other SVG elements change


JSFiddle example. The idea is, hovering over the big rectangle scales it in addition causing the other two smaller rectangles to scale too. Not vica versa.

HTML

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <g class="lower_element">
    <rect x="19" y="19" width="35" height="15" />
    <rect x="36" y="36" width="36.75" height="15"  />
  </g>  
    
  <g class="top">
    <rect x="149" y="100"  width="96.4" height="96.3"/>
  </g>
    
</svg>

CSS

svg {
    height: 220px;
    width: 400px;
    background: grey;
}

.lower_element  {
    fill: blue;
    transform-origin: center;
    transform-box: fill-box;
    transition-duration: 0.1s;
}

.lower_element:hover {
    transform: scale(1.7);
    -moz-transform: scale(1.7);
    -webkit-transform: scale(1.7);
    -o-transform: scale(1.7);
    -ms-transform: scale(1.7);
}

.top  {
   fill: blue;
   transform-origin: center;
   transform-box: fill-box;
   transition-duration: 0.1s;
}

.top:hover ~ .lower-element:hover ~ .lower-element  {
    transform: scale(1.7);
    -moz-transform: scale(1.7);
    -webkit-transform: scale(1.7);
    -o-transform: scale(1.7);
    -ms-transform: scale(1.7);
}

At present the two smaller rectangles are scaling. Hovering on the big rectangle has no effect. Tried to use ~ for lower_element, which seems to work with div elements, like in this example here, but it doesn't do the job in SVG.

PS. The solution is saved in the 1st mentioned JSFiddle. What I noticed while playing with the original SVG, which has more than two thousand lines of g code, that it didn't work as shown in JSFiddle. The problem was, the parent "top" element was mentioned below the sibling element. I assumed it would work, but it didn't. I was making a parallel with CSS whereas anything that is mentioned below will replace anything mentioned above and thus should work. Placing the parent "top" element above the sibling elements solved the issue.


Solution

  • your class name of lower_element is wrong in css. also try this:

    html:

    <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
      <g class="top">
        <rect x="149" y="100"  width="96.4" height="96.3"/>
      </g>
      <g class="lower_element">
        <rect x="19" y="19" width="35" height="15" />
        <rect x="36" y="36" width="36.75" height="15"  />
      </g>  
    </svg>
    

    css:

    svg {
      height: 220px;
      width: 400px;
      background: grey;
    }
    
    .lower_element {
      fill: white;
      transform-origin: center;
      transition-duration: 0.1s;
    }
    
    .top {
      fill: blue;
      transform-origin: center;
      transition-duration: 0.1s;
    }
    
    .top:hover + .lower_element {
      fill: red;
    }