2

I use Bold, Medium and Normal font weights on my website, that's 700, 500 and 400 respectively.

I use Helvetica Neue font and as a fallback for systems that doesn't have it installed I want to use Open Sans. The problem is Open Sans doesn't have Medium style.

I want my elements that I used to define as font-weight: 500 have font-weight: 600 if the browser uses Open Sans. Is it possible somehow?

There's a similar question at Stack Overflow: How to set different font-weight for fallback font? but I'cant get the result I need using techniqe described in an accepted answer.

I need something like

@font-face {
  font-family: 'semibold';
  src: 'Helvetica Neue':500, 'Open Sans':600;      
}

Not sure how to do it though.

Dmitry Samoylov
  • 1,228
  • 3
  • 17
  • 27

1 Answers1

0

You can't really define weight in a font-face declaration. Instead, font-weight is used there as a gatekeeper to match the font and not to pass styles to the element.

It seems like overkill, but you could use this JavaScript function by Sam Clarke as a starting point to see if the font is available, and then conditionally modify the font-weight following the logic that works best for your specific requirements.

For a simplified example with just these two fonts, you might set up the CSS like this:

@font-face {
  font-family: h-semibold;
  src: local('Helvetica Neue');
}

@font-face {
  font-family: os-semibold;
  src: local('Open Sans');
}

.semibold {
  font-family: h-semibold, os-semibold;
}

.w5 {
  font-weight: 500;
}

.w6 {
  font-weight: 600;
}

Then, using the function linked above, you put something like this in your JS to conditionally load the weight classes depending on font support:

var semibold = document.querySelectorAll('.semibold');

if (isFontAvailable('h-semibold')) {
    semibold.forEach(result => {
      result.className += ' ' + 'w5';
    });
} else {
    semibold.forEach(result => {
      result.className += ' ' + 'w6';
    });
}

You'll doubtless work out a more elegant solution if you really need to carry it through.

denmch
  • 1,446
  • 12
  • 20
  • But it there any way to do it without JS code? I think it won't work quite well in the SPA where parts of the page could be added dynamically and still have improper css classes. – Dmitry Samoylov Jan 25 '18 at 10:35