Search code examples
cssfont-face

using @font-face in codepen


Is it possible to use @font-face in an application like codepen.io?

I was trying to use a font from github in my codepen. But the font wouldn't load.

https://github.com/TypeNetwork/Decovar/blob/master/fonts/DecovarAlpha-VF.ttf

@font-face {
  font-family: "Decovar";
  src: url('https://github.com/TypeNetwork/Decovar/blob/master/fonts/DecovarAlpha-VF.ttf') format('truetype');
}

body {
  font-family: "Decovar";
}

UPDATE :: As pointed out there is a CORS issue with loading the font from github. But I don't really understand why I can use a link that loads a CSS stylesheet that defines a font family. But I can't write my own style sheet to include the font. How is one more secure than the other?

<link rel="stylesheet" media="screen" href="https://fontlibrary.org/face/decovar" type="text/css"/>

@font-face {
font-family: 'DecovarRegular24';
    src: url('/assets/fonts/decovar/434ee108e46e353c9914966b169d781b/b6a2e38c243d4f16ad98d2ca3d6cdc24/DecovarRegular24.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}

I did find this explanation at Mozilla.

This cross-origin sharing standard is used to enable cross-site HTTP requests for: ...Web Fonts (for cross-domain font usage in @font-face within CSS), so that servers can deploy TrueType fonts that can only be cross-site loaded and used by web sites that are permitted to do so.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

As pointed out by @jacob goh. The reason isn't for security. It's because:

Github is not a file hosting site and does not allow people to use it as such.


Solution

  • @font-face is not the problem. The problem is the font file you load.

    If the file hosting server has the right setting, CORS issue wouldn't occur.

    Github is not a file hosting site and does not allow people to use it as such.

    But there is a free service called Rawgit that can help with that.

    https://codepen.io/jacobgoh101/pen/YeWOay

    @font-face {
      font-family: "Decovar";
      src: url('https://cdn.rawgit.com/TypeNetwork/Decovar/620fb4ea/fonts/DecovarAlpha-VF.ttf') format('truetype');
    }
    
    body {
      font-family: "Decovar";
    }