Adding Google Fonts to a Drupal 8 theme

Some fonts on a web page

This took a bit more work to figure out than in Drupal 7! Bear in mind, this example is for installing a theme-wide (every page) font. There's references at the bottom where you might find further information on other methods.

Here's the old way of inserting Google Fonts (for every page using this theme):

function MYTHEME_preprocess_html(&$variables) {
  // this function is deprecated in D8 because, caching, I think
  drupal_add_css('//', array('group' => CSS_THEME));

In Drupal 8, however, we have to use the libraries method, which is "a bit" more involved. Firstly, we need to add a library to our (see last two lines). Here, I've made a subtheme of Bartik to implement the feature against. Side note: the base theme name is not capitalised. This didn't work when I tried it, but is ok all lower case. Seems a bizarre thing, when the original theme is declared like name: Bartik but there you go.

name: Blah
description: It's a theme
type: theme
base theme: bartik
core: 8.x
  - themeName/fonts

Then we need to create the library file. For whatever reason, the library is defined as themeName/libraryName in the .info.yml. The library file is called themeName.libraries.yml. The library file opens with a declaration of libraryName:

    name: SIL Open Font License, 1.1
      // { type: external }
      css/myStyles.css: {}

This YML file actually works fine without the license section, but it would be a bit poor to not even attempt to honour it... NB The font url has had the http: removed so that it is agnostic to secure-or-not connections at runtime.

If all that has worked, you should be able to view source on your site and see a comforting line of code like
<link rel="stylesheet" href="" media="all" />
All that remains is to implement the font in your CSS by inserting a rule in the myStyles.css file in the css folder, like:

font-family: 'Oxygen', sans-serif;


Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme -
Defining a theme with an .info.yml file -
Creating a Drupal 8 sub-theme -

Blog Tags: DrupalCSSPlanetThemes

Add new comment