Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "use" local "defs" in SVG

Tags:

html

svg

I have multiple SVG pictures embedded into single HTML page. Every SVG has own defs section that I am referencing to in my use elements. It looks like I can't define element with the same id inside multiple defs and reference to it. Second SVG use will pick the definition form the first SVG defs section, and ignore the local redefinition.

Does anybody know how I can reference to the LOCAL defs section?

The same story in Chrome and Firefox.

  1. See the example below:

    <html><head></head><body> <svg height="50" width="50">  <defs>   <rect id="mybox" height="40" width="40" style="fill:#00F;"></rect>  </defs>   <use xlink:href="#mybox"/> </svg> <svg height="50" width="50">  <defs>   <rect id="mybox" height="20" width="20" style="fill:#F00;"></rect>  </defs>   <use xlink:href="#mybox"/> </svg> </body></html> 
like image 636
drom Avatar asked Apr 20 '13 18:04

drom


People also ask

How do I use SVG DEFS?

The SVG <defs> element is used to embed definitions that can be reused inside an SVG image. Using the SVG <defs> elements you can group SVG shapes together and reuse them as a single shape. The shapes defined inside the <defs> element will be displayed when you reference it by a <use> element.

How do I reuse SVG elements?

The SVG <use> element can reuse an SVG shape from elsewhere in the SVG document, including <g> elements and <symbol> elements. The reused shape can be defined inside the <defs> element (which makes the shape invisible until used) or outside.

What is G in SVG?

The <g> element is used to group SVG shapes together. Once grouped you can transform the whole group of shapes as if it was a single shape. This is an advantage compared to a nested <svg> element which cannot be the target of transformation by itself.

What is a viewBox SVG?

The viewBox is an attribute of the SVG element in HTML. It is used to scale the SVG element that means we can set the coordinates as well as width and height. Syntax: viewBox = "min-x min-y width height" Attribute Values: min-x: It is used to set the horizontal axis.


1 Answers

An SVG file with multiple identical IDs is invalid per http://www.w3.org/TR/SVG/struct.html#IDAttribute

Your options are either make all the IDs unique or move the SVG into separate files and reference them via <object> or <iframe> tags.

like image 87
Robert Longson Avatar answered Sep 28 '22 01:09

Robert Longson