Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you place SVG defs in the head tag of an HTML document?

Tags:

html

svg

If you wanted to declare your SVG definitions globally can you define them in the header of the document or do you have to define them in body?

In the head:

<html>
   <head>
      <svg>
         <defs>
            <rect id="boxyBox" height="40" width="40" style="fill:#00F;"></rect>
            <rect id="circlyCircle" height="40" width="40" style="fill:#00F;"></rect>
         </defs> 
      </svg>
   </head>
   <body>
      <svg>
         <use xlink:href="#boxyBox"/>
         <use xlink:href="#circlyCircle"/>
      </svg>
   </body>
</html>

In the body:

<html>
   <head>
   </head>
   <body>
      <svg>
         <defs>
            <rect id="boxyBox" height="40" width="40" style="fill:#00F;"></rect>
            <rect id="circlyCircle" height="40" width="40" style="fill:#00F;"></rect>
         </defs> 
      </svg>
      <svg>
         <use xlink:href="#boxyBox"/>
         <use xlink:href="#circlyCircle"/>
      </svg>
   </body>
</html>

Here is the codepen. It appears to work in both cases.

It appears in the codepen at least, that you have to set the position to absolute in either case.

like image 943
1.21 gigawatts Avatar asked Jun 12 '17 04:06

1.21 gigawatts


People also ask

Can a SVG be embedded inside a HTML doc?

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.

How do I use SVG DEFS?

The <defs> in SVG is used whenever we want a particular element to render only when required or when it is called. objects that are created inside <defs> element are not rendered directly they are needed to be called by <use> element to render them on the browser. Property values: It does not have any property values.

What is the use of SVG tag in HTML?

Definition and Usage The <svg> tag defines a container for SVG graphics. SVG has several methods for drawing paths, boxes, circles, text, and graphic images.


1 Answers

You can't place SVG images (or any other kind of image) in the head of an HTML document, so it follows that you can't place any SVG elements in the head of an HTML document.

I mean, you "can", the document isn't going to refuse to render since it's HTML, not XHTML, but the svg element containing the defs will just get moved into the body as a separate SVG image (which you might have observed if you've tested this yourself beforehand) and, needless to say, it's simply invalid markup. That said, in both examples you have two separate SVG images (which is the reason why you seemingly have to apply absolute positioning) and you can clearly see that one has no trouble referencing the defs in the other.

like image 89
BoltClock Avatar answered Oct 13 '22 01:10

BoltClock