Four steps to add Google Fonts in Tailwind CSS

2021年04月28日 4034Browse 0Like 0Comments

This example shows how I added google fonts Rubik as the default font family in a React project.

Step 1: Get Google Fonts css code

  • Go to Google Fonts, and search the target font ('Rubik' here);
  • Click the found font to open the font family page, then click + Select this style button to choose ideal font styles. The selected font families with styles import code will appear on the right of this page;
  • Find and copy the <link> or @import code for importing font family's stylesheet

Step 2: Import the font css in /public/index.html

Note that I don't use @font-face to add the font family here, I use the link tag to import the remote stylesheet. The code is added in the head part of the html file.

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Rubik:wght@400;500;600;700&display=swap" rel="stylesheet">

Step 3: Extend added font families into the Tailwind default theme in tailwind.config.js

Note that I don't override the default provided font families. And this will get the fallback font families once failure of loading customized fonts.

const defaultTheme = require('tailwindcss/defaultTheme');  // import the defaul theme

module.exports = {
  purge: ['./src/**/*.js'],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {
      // Insert the custom font families at the beginning of the array
      fontFamily: {
        sans: ['Rubik', ...defaultTheme.fontFamily.sans],
      },
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

Step 4: Set customized font family as the app's default font

Add the following code in the root css file, mine is index.scss (the file which imports Tailwind utities)

@tailwind base;
@tailwind components;
@tailwind utilities;
// add the following lines
html {
  @apply font-sans
}

Reference

Sunflower

Stay hungry stay foolish

Comments