ratlan
ratlan

Reputation: 351

SVG doesn't use font when inside HTML

I have an SVG that displays fine in Chrome, but when I use it in an HTML page, it doesn't use the right font, instead using the default.

<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <style type="text/css">
      <![CDATA[
        /* latin-ext */
        @font-face {
          font-family: 'Roboto-Black';
          src: url(./Roboto-Black.ttf)
        }
      ]]>
    </style>
  </defs>
  <text style="font-family: 'Roboto-Black'; font-weight:normal;" transform="matrix(1, 0, 0, 1, 239.2, 51.394)">
    <tspan x="-101.469" y="27" font-family="Roboto-Black" font-size="72" fill="#000000">TEST</tspan>
  </text>
</svg>

The SVG displays fine in Chrome, but when displayed in an HTML page, it doesn't use the right font.

<html>
  <head></head>
  <body>
    <img src="test.svg" width="100%">
  </body>
</html>

What am I missing?


Addendum: Although a valid solution was offered below, I found it was easier to include the svg code directly in the html, instead of referencing an svg file. That way the problem doesn't arise.

Upvotes: 8

Views: 9796

Answers (3)

moojen
moojen

Reputation: 1352

Instead of incorporating/linking to a font, often you can also export the SVG using the option "Export text as curves for font independence". This is at least possible with Affinity Designer. This does make the file a bit heavier, but if you only use the font in this SVG, then of course it is much lighter overall.

Depending on the circumstance, this might be an option worth looking into.

Upvotes: 0

TheoPlatica
TheoPlatica

Reputation: 1271

How I solved it:

Instead of using the <img> tag, I have included the .svg file content:

<?php 
  $svg_file = file_get_contents(get_template_directory_uri().'/test.svg');
  echo $svg_file;
?>

Without being encapsulated inside the tag, the included .svg can require and use the font-family.

Upvotes: -1

Robert Longson
Robert Longson

Reputation: 124059

When used as an image (via an html <img> tag, an SVG <image> tag or as a CSS background-image) SVG must be consist of a single file in order to protect user privacy.

You can use a font, but you'll need to convert the font data to a data URI and embed the font in the SVG file.

Upvotes: 15

Related Questions