SVG shadow-root is closed

Артём Богосьян picture Артём Богосьян · Dec 10, 2017 · Viewed 26.3k times · Source

I have tried to animate an svg-sprite with CSS. I’ve created a sprite and injected it from gulp:

gulp.task('svgstore', function () {
var svgs = gulp
    .src('app/svg/*.svg')
    .pipe(svgmin(function (file) {
        return {
            plugins: [{
                cleanupIDs: {
                    minify: true
                }
            }]
        }
    }))        
    .pipe(svgstore({ inlineSvg: true }));

function fileContents (filePath, file) {
    return file.contents.toString();
}   

return gulp
    .src('app/*.html')
    .pipe(inject(svgs, { transform: fileContents }))
    .pipe(gulp.dest('app/'))
});

…and inserted images from the sprite to HTML:

<svg class="icon-ufo" >
    <use xlink:href="img/sprite.svg#ufo" aria-hidden="true"></use>
</svg>

And it works well, but the following image shows the shadow DOM is closed.

svg shadow dom

How I can to animate some styles of this SVG without JavaScript? But if JavaScript is the only way, how to do it better?

Answer

ccprog picture ccprog · Dec 10, 2017

The DOM of the referenced element is not part of the DOM of the referencing HTML page. It has isolated style sheets.

But the shadow element inherits styles from the referencing <use> element. This means that as long as the referenced element does not set the styles itself in the sprite or in a style sheet associated with the sprite, you can change (and animate) every inheritable style property on the icon by styling the <use> element.