Khashayar
Khashayar

Reputation: 47

How to Add a google font to Next.Js Project locally while using tailwind css

for a website that I want to create, I want to use the "Work Sans" Font from google. I downloaded "WorkSans-Black.ttf" file, created in the Folder "public" a subfolder "fonts" and threw the file in there. Following I have screenshoted the folder structure for you guys. Can anybody please help me, what are the next steps ?

enter image description here

Upvotes: 0

Views: 3674

Answers (1)

ptts
ptts

Reputation: 2086

1. Download Font

Download the font and place it in the public/font directory. I would suggest using this tool to download Google Fonts: https://google-webfonts-helper.herokuapp.com/fonts/work-sans?subsets=latin

2. Extend Tailwind's font stack with your font

// tailwind.config.js

const defaultTheme = require('tailwindcss/defaultTheme')

module.exports = {
  theme: {
    extend: {
      fontFamily: {
        sans: ['Work Sans', ...defaultTheme.fontFamily.sans],
      },
    },
  },
  // ...
}
// tailwind.css

@tailwind base;
@tailwind components;

// Repeat this for all the weights you downladed
@font-face {
  font-family: 'Work Sans';
  font-style: normal;
  font-weight: 400;
  src: local(''),
       url('public/fonts/work-sans-v9-latin-regular.woff2') format('woff2'),
       url('public/fonts/work-sans-v9-latin-regular.woff') format('woff');

@font-face {
  font-family: 'Work Sans';
  font-style: normal;
  font-weight: 100;
  src: local(''),
       url('public/fonts/work-sans-v9-latin-100.woff2') format('woff2'),
       url('public/fonts/work-sans-v9-latin-100.woff') format('woff');

@tailwind utilities;

3. (Optional) Preload font for performance

// Ref.: https://kirazhang.com/posts/nextjs-custom-fonts

import Head from "next/head";
import Link from "next/link";

export default function Layout {
    return (
    <div>
      <Head>
          <link
            rel="preload"
            href="public/fonts/work-sans-v9-latin-regular.woff2"
            as="font"
            crossOrigin=""
          />
          <link
            rel="preload"
            href="public/fonts/work-sans-v9-latin-100.woff2"
            as="font"
            crossOrigin=""
          />
        </Head>
            <body><Main /></body>
        </div>
    )
}

Upvotes: 6

Related Questions