Search code examples
javascriptcssfont-facecss-variables

string of only numbers not parsed correctly by CSS


font.newFileName is a string of only numbers: '000001101', '000001102', '000001103', so on and so forth.

If font.newFileName in new FontFace and setProperty is prefixed with a letter or changed to a${font.newFileName}, the script works...

...

fontList.forEach(font => {

  const
    ff = new FontFace(font.newFileName, `url('${font.newFilePath.replace(/\\/g, '/')}')`),
    fontItem = fontItemTemplate.content.cloneNode(true),
    fontNameElement = fontItem.querySelector('.font-name')

  ff.load().then(
    () => document.fonts.add(ff),
    err => console.error('ERROR:', err)
  )

  fontNameElement.style.setProperty('--font-family', font.newFileName)
  fontNameElement.style.fontFamily = 'var(--font-family)'

  ...

Does anybody know why this is the case?

Also, is there some way to use the font.newFileName values as they are without having to prefix a letter to the front?


Solution

  • The CSS font-family property does not accept font names that start with a number(if unquoted)1.

    To make it work you can put it in quotes. Something like:

    fontList.forEach(font => {
        // ...rest
    
      ff.load().then(
        () => document.fonts.add(ff),
        err => console.error('ERROR:', err)
      )
    
      fontNameElement.style.setProperty('--font-family', `'${font.newFileName}'`);
      fontNameElement.style.fontFamily = 'var(--font-family)'
    
      ...
    });
    

    References:

    1. Valid Font Family names
    2. Font Family property
    3. Examples of valid identifier names*

    * Not related to this post but good to refer