如何在 Next.js 项目的 tailwind css 中使用 google 字体

问题描述 投票:0回答:4

我在 Next.js 中有一个项目,但不知道如何将 Google Font 与 Tailwind CSS 结合使用。

next.js tailwind-css custom-font google-fonts
4个回答
8
投票

首先,您必须在styles文件夹中的globals.css中添加导入的字体Url,以及对于React.js它将是src文件夹中的index.css

例如

@import url("https://fonts.googleapis.com/css2?family=Play:wght@400;700&display=swap");

@tailwind base;
@tailwind components;
@tailwind utilities;

然后在tailwind.config.js文件中扩展modules.exports

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      fontFamily: {
        play: ["Play", "sans-serif"],
      },
    },
  },
  plugins: [],
};

最后,您可以在任何地方使用此字体,例如

<h2 className="font-play text-5xl font-bold uppercase">
  Hello World!
</h2>


5
投票

根据文档,您需要执行此操作才能使其与 TailWind 和 Next13 一起使用

首先将

next/font/google
导入到您的
_app.ts
。并创建一个字体变量。

import Layout from '@/components/layout/Layout'
import '@/styles/globals.css'
import type { AppProps } from 'next/app
import { Kalam } from 'next/font/google';

const kalam = Kalam({ 
  subsets: ['latin'],
  weight:["400"],
  variable: '--font-kalam',
});

export default function App({ Component, pageProps }: AppProps) {
  return (

    <main className={`${kalam.variable}`}>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </main>
  )
}

然后去你的

tailwind.config.js
并扩展你的字体系列。

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {
      fontFamily: {
        kalam: ['var(--font-kalam)'],
      },
    },
    container: {
      // you can configure the container to be centered
      center: true,
      // or have default horizontal padding
      padding: '1rem',

      // default breakpoints but with 40px removed
      screens: {
        sm: '500px',
        md: '628px',
        lg: '884px',
        xl: '1140px',
        '2xl': '1296px',
      },
    },
  },
  plugins: [],
}

要在代码中使用它,只需添加

font-kalam
作为您的类即可。

请参阅文档此处


0
投票
@tailwind base;
@tailwind components;
@tailwind utilities;

@import url("https://fonts.googleapis.com/css2?family=Play:wght@400;700&display=swap");

只需在顺风注释后添加导入行即可完美加载字体。希望有帮助!


-3
投票

在 React Js 中

第1步:在index.css中导入Google字体

@import url('https://fonts.googleapis.com/css2?family=Pacifico&display=swap');

第 2 步:在 Tailwind CSS 中配置 Google 字体

const defaultTheme = require('tailwindcss/defaultTheme');

module.exports = {
  theme: {
    extend: {
      fontFamily: {
          pacifico: ['"Pacifico"', ...defaultTheme.fontFamily.sans],
      }
    }
  },
}

第 3 步:使用您的自定义谷歌字体

<h1 class="pacifico">Pacifico is Google Font</h1>
© www.soinside.com 2019 - 2024. All rights reserved.