Search code examples
cssfontsmaterial-uijsscss-in-js

Migrating fonts stack from SCSS to JSS (cssinjs)


We're utilizing a lot of custom fonts with varying weights for various purposes. Now that our whole stack is using Material UI with JSS theming and styling, we'd like to get rid of the last few .scss files in our folder architecture.

All of the fonts are working perfectly with the SCSS syntax as of now.

We have an index.scss file imported in the main entry point of the app. It has a single line in it:

@import 'styles/fonts';

styles/_fonts.scss contains a lot of font faces:

@font-face {
    font-family: 'FooFont';
    src: url('styles/fonts/FooFont_LtIt.ttf') format('truetype');
    font-weight: 200;
    font-style: normal;
}

And the styles/fonts folder has all of the font files in it.

I have already succeeded in attaching global Material UI makeStyles styling to the head. This allows me to inject global CSS instead of component-based JSS:

'@global': {
    '@font-face': [
      {
        fontFamily: 'FooFont',
        src: 'url("styles/fonts/FooFont_Rg.ttf") format("truetype")',
        fontWeight: 400,
        fontStyle: 'normal',
      }
    ],
    '*': {
      boxSizing: 'border-box',
    },
    html: {
      height: '100%',
    },
...

This syntax adds a <style> tag at the bottom of the <head> and applies the styles. This works for non-font styling.

The main issue with this: For some reason, it doesn't update my font stack. The fonts are downloaded, but the page elements still use the fallback font.

I have also tried using JSS directly and injecting the CSS at the top of the <head>. No luck. Writing fonts manually into the <style> tags at the top of the head downloads the font (I can see them appearing in the Network tab) but the page elements update and still use the fallback font.


Solution

  • Can you just add the fonts in an inline style tag in your index.html?

    That way they will load right away and be available to your other code.

    I use CSS in JS a lot but always load fonts in my root index file.

    So just do this in your index.html

    <head>
    <style type="text/css">
     @font-face {
        font-family: 'FooFont';
        src: url('styles/fonts/FooFont_LtIt.ttf') format('truetype');
        font-weight: 200;
        font-style: normal;
    }
    </style>
    </head>
    

    Then you can manage all your other styles whatever way you want