Adam Scott Adam Scott - 7 months ago 15
HTML Question

Animate a <g> element in SVG with CSS

In an SVG I have a

<g class="building">
that I'd like to move upwards on hover.

<svg x="0px" y="0px"
viewBox="0 0 595.3 841.9" style="enable-background:new 0 0 595.3 841.9;" xml:space="preserve">
<g class="building">
<rect id="XMLID_1_" x="128.6" y="296.2"/>
</g>
</svg>


If the was a
<div class="building">
, the CSS that I'd use would be:

.building {
position: relative;
top: -20px;
}


As
position
and
top
does not work in SVG, I'll obviously have to do this another way

How do I move up
<g class="building">
20px?

Here's a fiddle

Answer

You can use a CSS transform to move it. Be careful as you've the same class defined for the g and the rect, you might want to reconsider that.

	.building{fill:#72B62B;stroke:#000000;stroke-miterlimit:10;}
	.ground{fill:#030203;stroke:#000000;stroke-miterlimit:10;}
  
  .building:hover {
    transform: translateY(-30px);
  }
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
	 viewBox="0 0 595.3 841.9" style="enable-background:new 0 0 595.3 841.9;" xml:space="preserve">
<g class="building">
<rect id="XMLID_2_" x="21.6" y="645" class="building" width="550" height="74.3"/>
</g>

Comments