3
votes

I'm trying to solve problem with fonts. We have bought Helvetica Light font and we have linked it via font face. In CSS we have font-family: 'Helvetica', 'Arial', sans-serif;.

Now when someone doesn't have Helvetica font installed in computer (Windows users mostly) they can see Light version correctly but they don't see Bold Helvetica correctly, because it uses closest font-weight of that font.

My question is whether it's possible or not to specify that if particular font-weight isn't available to use next font - Arial in this case.

Thanks to everyone who will try to help me.

1

1 Answers

2
votes

One way could be using a small script, which looks for a class, .need-bold, and when found, iterate its fonts and test if bold exists, and if, adds a new style with the class to override the initial one.

function getWidthNum(elem) {
  return parseFloat(window.getComputedStyle(elem,null).getPropertyValue('width'));
}
(function(elem) {
  var tst = document.createElement('span');
  tst.textContent = 'abcdefghijklmnopqrstuvwxyz0123456789';
  tst.style = 'position:absolute;left:-9999px;display:inline-block;font-size:20px;';
  document.body.appendChild(tst);
  var fonts = window.getComputedStyle(elem,null).getPropertyValue('font-family').split(',');
  for (var i = 0; i < fonts.length; i++) {
    tst.style.fontFamily = fonts[i];
    tst.style.fontWeight = 'bold';
    var w = getWidthNum(tst);
    tst.style.fontWeight = 'normal';
    if (w > getWidthNum(tst)) {
      var sheet = document.createElement('style')
      sheet.innerHTML = ".need-bold {font-family: '" + fonts[i] + "';}";
      document.body.appendChild(sheet);
      break;
    }
  }
  document.body.removeChild(tst);
})(document.querySelector('.need-bold'));
.need-bold {
  font-family: 'Helvetica', 'Times New Roman', Georgia;
}
<span class="need-bold">Hello World</span>