-->

Force Chrome to use external font in CSS

2019-04-28 02:46发布

问题:

It took me a long time to figure out, that Chrome always prefers local installed fonts over a font with the same name that is linked in the css (See also https://stackoverflow.com/a/27704394/1099519). My problem is how to figure out, to force Chrome not to do so.

On my page https://www.amon.cc/ I use "Roboto Light" from Google Fonts (https://fonts.google.com/specimen/Roboto), like this:

<link href="//fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet" type="text/css" />

In my CSS file the font is declared like this:

body{
  ...
  font-family:Roboto,...;
  font-weight:300;
 ....
}

Which works perfectly fine in FF, IE, Edge:

But the font is always thicker in Chrome:

The reason: On my private Windows 10 and also on by business computer the font "Roboto" is pre-installed on Windows: Robot Regular, Robot Condensed. But there is no Roboto Thin or Robot Light, so it seems Chrome has a fallback to Roboto Regular.

When deleting the Robot fontset from Windows, Chrome uses the declared web font and displays it the way I want it. I could not figure out, how to "force" Chrome not to use the local installation and instead use the on the CDN.

However, Chrome can display the Roboto font in all different variants on the https://fonts.google.com/specimen/Roboto website (even with my local installed Robot font). I couldn't find out the trick how this has been done.

回答1:

You can rename the font in your CSS and still use the distant woff file. For example:

@font-face {
  font-family: 'RobotoBis';
  font-style: normal;
  font-weight: 300;
  src: local('Roboto Light'), local('Roboto-Light'), url(http://fonts.gstatic.com/s/roboto/v15/Pru33qjShpZSmG3z6VYwnRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
  unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}


@font-face {
  font-family: 'RobotoBis';
  font-style: normal;
  font-weight: 300;
  src: local('Roboto Light'), local('Roboto-Light'), url(http://fonts.gstatic.com/s/roboto/v15/Hgo13k-tfSpn0qi1SFdUfVtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
h1 {
  font-family: RobotoBis;
}
<h1>Hello world !</h1>

But the dark side of this method is that Google can change the font URL in the future (that is mainly probable). So host you own font files to avoid this problem.

And of course, it can be apply only for the websites you own and where you can customize the CSS...