Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you load and use a custom font in Svelte

Tags:

fonts

svelte

I know it probably uses @font-face but I dont know where to put my woff files localy to get Svelte to use a custom font. I dont know where to put the @font-face either. Thanks in advance!

like image 740
Eddysanoli Avatar asked Aug 31 '25 04:08

Eddysanoli


2 Answers

If you are using Sveltekit, you can load fonts locally using the static directory.

Store your font files under static/fonts, and then use either a CSS file or a <style> tag to reference your font files.

/* fonts.css */

@font-face {
    font-family: 'Lora';
    font-style: normal;
    font-weight: 500;
    src: url('/fonts/lora-v20-latin-500.eot'); /* IE9 Compat Modes */
    src: local(''), url('/fonts/lora-v20-latin-500.eot?#iefix') format('embedded-opentype'),
        /* IE6-IE8 */ url('/fonts/lora-v20-latin-500.woff2') format('woff2'),
        /* Super Modern Browsers */ url('/fonts/lora-v20-latin-500.woff') format('woff'),
        /* Modern Browsers */ url('/fonts/lora-v20-latin-500.ttf') format('truetype'),
        /* Safari, Android, iOS */ url('/fonts/lora-v20-latin-500.svg#Lora') format('svg'); /* Legacy iOS */
}

Finally, just import the CSS file in your __layout.svelte file:

<!-- __layout.svelte -->

<script lang="ts">
    import '/styles/fonts.css';
</script>
like image 126
Esteban Borai Avatar answered Sep 02 '25 22:09

Esteban Borai


Svelte doesn't require anything special to use fonts.

You can inline a @font-face in your stylesheet or inside any .svelte file's <style> tag:

<h1>Hello World!</h1>

<style>
    @font-face {
        font-family: 'Gelasio';
        font-style: normal;
        font-weight: 400;
        src: local('Gelasio Regular'), local('Gelasio-Regular'), url(https://fonts.gstatic.com/s/gelasio/v1/cIf9MaFfvUQxTTqS9C6hYQ.woff2) format('woff2');
        unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
    }

    h1 {
        font-family: Gelasio
    }
</style>

Alternatively, you can include the font with a <link> inside the head. For this approach <svelte:head> is handy:

<svelte:head>
  <link href="https://fonts.googleapis.com/css?family=Gelasio" rel="stylesheet">
</svelte:head>
like image 40
joshnuss Avatar answered Sep 02 '25 23:09

joshnuss