omega
omega

Reputation: 43833

How to use css3 animations on svg object tags?

I load a svg file into an object tag, and I want to animate it. I have a simple code here for a test, but there is a problem:

In my second css rule, I target #main, which happens to be the id of a g in side the svg element. I expect the g tag to animate, but it does not. If I replace the #main with #svgA, then it works. Does anyone know how to target contents of svg tags with css3?

Thanks

<!DOCTYPE html>
<html>
    <head>
        <title>Title of the document</title>

        <style>
            /* The animation code */
            @keyframes example {
                from {
                    left:0px;
                }
                to {
                    left:100px;
                }
            }

            /* The element to apply the animation to */
            #main {
                position:relative;
                animation-name: example;
                animation-duration: 4s;
            } 

        </style>


    </head>

    <body>
        <object class="svgA" data="images/yeti/yeti-01.svg" type="image/svg+xml"></object>
    </body>

</html> 

Upvotes: 1

Views: 791

Answers (2)

Kevinleary.net
Kevinleary.net

Reputation: 9670

Because the SVG is dynamically loaded you need to load the stylesheet from within the SVG itself. Try adding this to your SVG:

<?xml-stylesheet href="anim.css" type="text/css"?>

Where anim.css is the stylesheet where your CSS3 animations are defined.

Upvotes: 2

nikhil
nikhil

Reputation: 411

You can use transform to animate svg elements.

/* The animation code */
@keyframes example {
  from {
    transform: translateX(0px);
  }
  to {
    transform: translateX(100px);
  }
}

/* The element to apply the animation to */
#main {
  position:relative;
  animation-name: example;
  animation-duration: 4s;
} 
<svg>
    <g id="main">
         <circle cx="50" cy="50" r="40" fill="red" />
    </g>
</svg>

Upvotes: -1

Related Questions