Can you put SVG defs in the main tag of an HTML document?

If you want to declare your SVG definitions globally, can you define them in the document header, or do you need to define them in the body?

In my 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 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 seems to work in both cases.

At least in codeped you should set the absolute position anyway.

+3


source to share


1 answer


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



I mean, you "can", the document won't give up on rendering as it's HTML, not XHTML, but the element svg

containing the defs will just be moved into the body as a separate SVG image (which you might notice if you would have tested it yourself beforehand), and of course this is just the wrong markup. However, in both examples, you have two separate SVG images (which is why you seem to have to apply absolute positioning), and you can clearly see that there is no problem referencing defs in the other.

+2


source







All Articles