Skip to content

字体

¥Font

next/font 会自动优化你的字体(包括自定义字体),并移除外部网络请求,以提高隐私性和性能。

¥next/font automatically optimizes your fonts (including custom fonts) and removes external network requests for improved privacy and performance.

它内置了任何字体文件的自动自托管功能。这意味着即使没有 布局转变,你也可以以最佳方式加载 Web 字体。

¥It includes built-in automatic self-hosting for any font file. This means you can optimally load web fonts with no layout shift.

你也可以方便地使用所有 谷歌字体。CSS 和字体文件在构建时下载,并与其余静态资源一起自托管。浏览器不会向 Google 发送任何请求。

¥You can also conveniently use all Google Fonts. CSS and font files are downloaded at build time and self-hosted with the rest of your static assets. No requests are sent to Google by the browser.

tsx
import { Inter } from 'next/font/google'

// If loading a variable font, you don't need to specify the font weight
const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
})

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={inter.className}>
      <body>{children}</body>
    </html>
  )
}

🎥 观看:了解有关使用 next/fontYouTube(6 分钟) 的更多信息。

¥🎥 Watch: Learn more about using next/fontYouTube (6 minutes).

参考

¥Reference

font/googlefont/local类型必需
src字符串或对象数组
weight字符串或数组必需/可选
style字符串或数组*
subsets字符串数组*
axes字符串数组*
display字符串*
preload布尔值*
fallback字符串数组*
adjustFontFallback布尔值或字符串*
variable字符串*
declarations对象数组*

src

字体文件的路径,作为字符串或对象数组(类型为 Array<{path: string, weight?: string, style?: string}>),相对于调用字体加载器函数的目录。

¥The path of the font file as a string or an array of objects (with type Array<{path: string, weight?: string, style?: string}>) relative to the directory where the font loader function is called.

用于 next/font/local

¥Used in next/font/local

  • 必需

    ¥Required

示例:

¥Examples:

  • src:'./fonts/my-font.woff2',其中 my-font.woff2 放置在 app 目录内名为 fonts 的目录中

    ¥src:'./fonts/my-font.woff2' where my-font.woff2 is placed in a directory named fonts inside the app directory

  • src:[{path: './inter/Inter-Thin.ttf', weight: '100',},{path: './inter/Inter-Regular.ttf',weight: '400',},{path: './inter/Inter-Bold-Italic.ttf', weight: '700',style: 'italic',},]

  • 如果使用 src:'../styles/fonts/my-font.ttf'app/page.tsx 中调用字体加载器函数,则 my-font.ttf 被放置在项目根目录下的 styles/fonts

    ¥if the font loader function is called in app/page.tsx using src:'../styles/fonts/my-font.ttf', then my-font.ttf is placed in styles/fonts at the root of the project

weight

字体 weight 具有以下可能性:

¥The font weight with the following possibilities:

  • 一个字符串,其中包含特定字体可用的权重值或一系列值(如果是 variable 字体)

    ¥A string with possible values of the weights available for the specific font or a range of values if it's a variable font

  • 如果字体不是 可变谷歌字体,则为权重值数组。仅适用于 next/font/google

    ¥An array of weight values if the font is not a variable google font. It applies to next/font/google only.

用于 next/font/googlenext/font/local

¥Used in next/font/google and next/font/local

  • 如果使用的字体不是 variable,则为必填项

    ¥Required if the font being used is not variable

示例:

¥Examples:

  • weight: '400':单个权重值的字符串 - 对于字体 Inter,可能的值为 '100''200''300''400''500''600''700''800''900''variable',其中 'variable' 是默认值)

    ¥weight: '400': A string for a single weight value - for the font Inter, the possible values are '100', '200', '300', '400', '500', '600', '700', '800', '900' or 'variable' where 'variable' is the default)

  • weight: '100 900':可变字体的 100900 范围之间的字符串

    ¥weight: '100 900': A string for the range between 100 and 900 for a variable font

  • weight: ['100','400','900']:非可变字体的 3 个可能值的数组

    ¥weight: ['100','400','900']: An array of 3 possible values for a non variable font

style

字体 style 具有以下可能性:

¥The font style with the following possibilities:

  • 字符串 value,默认值为 'normal'

    ¥A string value with default value of 'normal'

  • 如果字体不是 可变谷歌字体,则为样式值数组。仅适用于 next/font/google

    ¥An array of style values if the font is not a variable google font. It applies to next/font/google only.

用于 next/font/googlenext/font/local

¥Used in next/font/google and next/font/local

  • 可选

    ¥Optional

示例:

¥Examples:

  • style: 'italic':字符串 - next/font/google 可以是 normalitalic

    ¥style: 'italic': A string - it can be normal or italic for next/font/google

  • style: 'oblique':字符串 - 它可以为 next/font/local 取任何值,但预计来自 标准字体样式

    ¥style: 'oblique': A string - it can take any value for next/font/local but is expected to come from standard font styles

  • style: ['italic','normal']next/font/google 的 2 个值的数组 - 值来自 normalitalic

    ¥style: ['italic','normal']: An array of 2 values for next/font/google - the values are from normal and italic

subsets

字体 subsets 由字符串值数组定义,其中包含你希望成为 preloaded 的每个子集的名称。当 preload 选项为 true(默认值)时,通过 subsets 指定的字体将在头部注入一个链接预加载标记。

¥The font subsets defined by an array of string values with the names of each subset you would like to be preloaded. Fonts specified via subsets will have a link preload tag injected into the head when the preload option is true, which is the default.

用于 next/font/google

¥Used in next/font/google

  • 可选

    ¥Optional

示例:

¥Examples:

  • subsets: ['latin']:具有子集 latin 的数组

    ¥subsets: ['latin']: An array with the subset latin

你可以在 Google Fonts 页面上找到你的字体的所有子集的列表。

¥You can find a list of all subsets on the Google Fonts page for your font.

axes

某些可变字体具有可以包含的额外 axes。默认情况下,仅包含字体粗细以减小文件大小。axes 的可能值取决于特定字体。

¥Some variable fonts have extra axes that can be included. By default, only the font weight is included to keep the file size down. The possible values of axes depend on the specific font.

用于 next/font/google

¥Used in next/font/google

  • 可选

    ¥Optional

示例:

¥Examples:

  • axes: ['slnt']Inter 可变字体的值为 slnt 的数组,其中 slnt 作为附加 axes,如 此处 所示。你可以通过使用 Google 可变字体页面 上的过滤器并查找 wght 以外的轴来找到字体可能的 axes

    ¥axes: ['slnt']: An array with value slnt for the Inter variable font which has slnt as additional axes as shown here. You can find the possible axes values for your font by using the filter on the Google variable fonts page and looking for axes other than wght

display

字体 display 可能带有 'auto''block''swap''fallback''optional' 的字符串 values,默认值为 'swap'

¥The font display with possible string values of 'auto', 'block', 'swap', 'fallback' or 'optional' with default value of 'swap'.

用于 next/font/googlenext/font/local

¥Used in next/font/google and next/font/local

  • 可选

    ¥Optional

示例:

¥Examples:

  • display: 'optional':分配给 optional 值的字符串

    ¥display: 'optional': A string assigned to the optional value

preload

一个布尔值,指定字体是否应为 preloaded。默认值为 true

¥A boolean value that specifies whether the font should be preloaded or not. The default is true.

用于 next/font/googlenext/font/local

¥Used in next/font/google and next/font/local

  • 可选

    ¥Optional

示例:

¥Examples:

  • preload: false

fallback

无法加载字体时使用的后备字体。没有默认值的后备字体字符串数组。

¥The fallback font to use if the font cannot be loaded. An array of strings of fallback fonts with no default.

  • 可选

    ¥Optional

用于 next/font/googlenext/font/local

¥Used in next/font/google and next/font/local

示例:

¥Examples:

  • fallback: ['system-ui', 'arial']:将后备字体设置为 system-uiarial 的数组

    ¥fallback: ['system-ui', 'arial']: An array setting the fallback fonts to system-ui or arial

adjustFontFallback

  • 对于 next/font/google:一个布尔值,设置是否应使用自动后备字体来减少 累积布局偏移。默认值为 true

    ¥For next/font/google: A boolean value that sets whether an automatic fallback font should be used to reduce Cumulative Layout Shift. The default is true.

  • 对于 next/font/local:字符串或布尔值 false 值,用于设置是否应使用自动后备字体来减少 累积布局偏移。可能的值为 'Arial''Times New Roman'false。默认值为 'Arial'

    ¥For next/font/local: A string or boolean false value that sets whether an automatic fallback font should be used to reduce Cumulative Layout Shift. The possible values are 'Arial', 'Times New Roman' or false. The default is 'Arial'.

用于 next/font/googlenext/font/local

¥Used in next/font/google and next/font/local

  • 可选

    ¥Optional

示例:

¥Examples:

  • adjustFontFallback: false:用于 next/font/google

    ¥adjustFontFallback: false: for next/font/google

  • adjustFontFallback: 'Times New Roman':用于 next/font/local

    ¥adjustFontFallback: 'Times New Roman': for next/font/local

variable

一个字符串值,用于定义样式与 CSS 变量方法.css 一起应用时要使用的 CSS 变量名称。

¥A string value to define the CSS variable name to be used if the style is applied with the CSS variable method.

用于 next/font/googlenext/font/local

¥Used in next/font/google and next/font/local

  • 可选

    ¥Optional

示例:

¥Examples:

  • variable: '--my-font':CSS 变量 --my-font 被声明

    ¥variable: '--my-font': The CSS variable --my-font is declared

declarations

字体 descriptor 键值对数组,进一步定义生成的 @font-face

¥An array of font face descriptor key-value pairs that define the generated @font-face further.

用于 next/font/local

¥Used in next/font/local

  • 可选

    ¥Optional

示例:

¥Examples:

  • declarations: [{ prop: 'ascent-override', value: '90%' }]

示例

¥Examples

谷歌字体

¥Google Fonts

要使用 Google 字体,请将其作为函数从 next/font/google 导入。我们建议使用 可变字体 以获得最佳性能和灵活性。

¥To use a Google font, import it from next/font/google as a function. We recommend using variable fonts for the best performance and flexibility.

tsx
import { Inter } from 'next/font/google'

// If loading a variable font, you don't need to specify the font weight
const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
})

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={inter.className}>
      <body>{children}</body>
    </html>
  )
}

如果你不能使用可变字体,则需要指定粗细:

¥If you can't use a variable font, you will need to specify a weight:

tsx
import { Roboto } from 'next/font/google'

const roboto = Roboto({
  weight: '400',
  subsets: ['latin'],
  display: 'swap',
})

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={roboto.className}>
      <body>{children}</body>
    </html>
  )
}

你可以使用数组指定多个权重和/或样式:

¥You can specify multiple weights and/or styles by using an array:

需要了解:对于包含多个单词的字体名称使用下划线 (_)。例如Roboto Mono 应作为 Roboto_Mono 导入。

¥Good to know: Use an underscore (_) for font names with multiple words. E.g. Roboto Mono should be imported as Roboto_Mono.

指定子集

¥Specifying a subset

Google 字体自动为 subset。这会减小字体文件的大小并提高性能。你需要定义要预加载的子集。当 preloadtrue 时未能指定任何子集将导致警告。

¥Google Fonts are automatically subset. This reduces the size of the font file and improves performance. You'll need to define which of these subsets you want to preload. Failing to specify any subsets while preload is true will result in a warning.

这可以通过将其添加到函数调用中来完成:

¥This can be done by adding it to the function call:

tsx
const inter = Inter({ subsets: ['latin'] })

查看 字体 API 参考 了解更多信息。

¥View the Font API Reference for more information.

使用多种字体

¥Using Multiple Fonts

你可以在应用中导入和使用多种字体。你可以采取两种方法。

¥You can import and use multiple fonts in your application. There are two approaches you can take.

第一种方法是创建一个实用程序函数,用于导出字体、导入字体并在需要时应用其 className。这确保字体仅在渲染时才预加载:

¥The first approach is to create a utility function that exports a font, imports it, and applies its className where needed. This ensures the font is preloaded only when it's rendered:

ts
import { Inter, Roboto_Mono } from 'next/font/google'

export const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
})

export const roboto_mono = Roboto_Mono({
  subsets: ['latin'],
  display: 'swap',
})
tsx
import { inter } from './fonts'

export default function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={inter.className}>
      <body>
        <div>{children}</div>
      </body>
    </html>
  )
}
tsx
import { roboto_mono } from './fonts'

export default function Page() {
  return (
    <>
      <h1 className={roboto_mono.className}>My page</h1>
    </>
  )
}

上例中,Inter 会全局应用,Roboto Mono 可以根据需要导入应用。

¥In the example above, Inter will be applied globally, and Roboto Mono can be imported and applied as needed.

或者,你可以创建 CSS 变量 并将其与你首选的 CSS 解决方案一起使用:

¥Alternatively, you can create a CSS variable and use it with your preferred CSS solution:

tsx
import { Inter, Roboto_Mono } from 'next/font/google'
import styles from './global.css'

const inter = Inter({
  subsets: ['latin'],
  variable: '--font-inter',
  display: 'swap',
})

const roboto_mono = Roboto_Mono({
  subsets: ['latin'],
  variable: '--font-roboto-mono',
  display: 'swap',
})

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}>
      <body>
        <h1>My App</h1>
        <div>{children}</div>
      </body>
    </html>
  )
}
css
html {
  font-family: var(--font-inter);
}

h1 {
  font-family: var(--font-roboto-mono);
}

在上面的示例中,Inter 将全局应用,任何 <h1> 标签都将使用 Roboto Mono 进行样式设置。

¥In the example above, Inter will be applied globally, and any <h1> tags will be styled with Roboto Mono.

建议:谨慎使用多种字体,因为每种新字体都是客户端必须下载的额外资源。

¥Recommendation: Use multiple fonts conservatively since each new font is an additional resource the client has to download.

本地字体

¥Local Fonts

导入 next/font/local 并指定本地字体文件的 src。我们建议使用 可变字体 以获得最佳性能和灵活性。

¥Import next/font/local and specify the src of your local font file. We recommend using variable fonts for the best performance and flexibility.

tsx
import localFont from 'next/font/local'

// Font files can be colocated inside of `app`
const myFont = localFont({
  src: './my-font.woff2',
  display: 'swap',
})

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={myFont.className}>
      <body>{children}</body>
    </html>
  )
}

如果你想对单个字体系列使用多个文件,src 可以是一个数组:

¥If you want to use multiple files for a single font family, src can be an array:

查看 字体 API 参考 了解更多信息。

¥View the Font API Reference for more information.

使用 Tailwind CSS

¥With Tailwind CSS

next/font 使用 CSS 变量Tailwind CSS 无缝集成。

¥next/font integrates seamlessly with Tailwind CSS using CSS variables.

在下面的示例中,我们使用 next/font/google 中的 InterRoboto_Mono 字体(你可以使用任何 Google 字体或本地字体)。使用 variable 选项定义 CSS 变量名,例如分别将这两个字体命名为 interroboto_mono。然后,应用 inter.variableroboto_mono.variable 将 CSS 变量添加到 HTML 文档中。

¥In the example below, we use the Inter and Roboto_Mono fonts from next/font/google (you can use any Google Font or Local Font). Use the variable option to define a CSS variable name, such as inter and roboto_mono for these fonts, respectively. Then, apply inter.variable and roboto_mono.variable to include the CSS variables in your HTML document.

需要了解:你可以根据自己的偏好、样式需求或项目要求,将这些变量添加到 <html><body> 标签中。

¥Good to know: You can add these variables to the <html> or <body> tag, depending on your preference, styling needs or project requirements.

tsx
import { Inter, Roboto_Mono } from 'next/font/google'

const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-inter',
})

const roboto_mono = Roboto_Mono({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-roboto-mono',
})

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html
      lang="en"
      className={`${inter.variable} ${roboto_mono.variable} antialiased`}
    >
      <body>{children}</body>
    </html>
  )
}

最后,将 CSS 变量添加到 Tailwind CSS 配置

¥Finally, add the CSS variable to your Tailwind CSS config:

Tailwind CSS v4

Tailwind v4 开始,默认情况下无需任何配置。如果你确实需要配置 Tailwind,可以按照 官方文档 中的说明配置全局 CSS 文件。

¥As of Tailwind v4, there is zero configuration required by default. If you do need to configure Tailwind, you can follow the official documentation for configuring the global CSS file.

Tailwind CSS v3

你现在可以使用 font-sansfont-mono 实用程序类将字体应用到你的元素。

¥You can now use the font-sans and font-mono utility classes to apply the font to your elements.

<p class="font-sans ...">The quick brown fox ...</p>
<p class="font-mono ...">The quick brown fox ...</p>

应用样式

¥Applying Styles

你可以通过三种方式应用字体样式:

¥You can apply the font styles in three ways:

className

返回一个只读 CSS className,用于将加载的字体传递给 HTML 元素。

¥Returns a read-only CSS className for the loaded font to be passed to an HTML element.

tsx
<p className={inter.className}>Hello, Next.js!</p>

style

返回一个只读 CSS style 对象,用于将加载的字体传递给 HTML 元素,包括 style.fontFamily 以访问字体系列名称和后备字体。

¥Returns a read-only CSS style object for the loaded font to be passed to an HTML element, including style.fontFamily to access the font family name and fallback fonts.

tsx
<p style={inter.style}>Hello World</p>

CSS 变量

¥CSS Variables

如果你想在外部样式表中设置样式并在其中指定其他选项,请使用 CSS 变量方法。

¥If you would like to set your styles in an external style sheet and specify additional options there, use the CSS variable method.

除了导入字体之外,还要导入定义 CSS 变量的 CSS 文件,并设置字体加载器对象的变量选项,如下所示:

¥In addition to importing the font, also import the CSS file where the CSS variable is defined and set the variable option of the font loader object as follows:

tsx
import { Inter } from 'next/font/google'
import styles from '../styles/component.module.css'

const inter = Inter({
  variable: '--font-inter',
})

要使用该字体,请将要设置样式的文本的父容器的 className 设置为字体加载器的 variable 值,并将文本的 className 设置为外部 CSS 文件中的 styles 属性。

¥To use the font, set the className of the parent container of the text you would like to style to the font loader's variable value and the className of the text to the styles property from the external CSS file.

tsx
<main className={inter.variable}>
  <p className={styles.text}>Hello World</p>
</main>

component.module.css CSS 文件中定义 text 选择器类,如下所示:

¥Define the text selector class in the component.module.css CSS file as follows:

css
.text {
  font-family: var(--font-inter);
  font-weight: 200;
  font-style: italic;
}

在上面的示例中,文本 Hello World 使用 Inter 字体设置样式,并使用 font-weight: 200font-style: italic 生成后备字体。

¥In the example above, the text Hello World is styled using the Inter font and the generated font fallback with font-weight: 200 and font-style: italic.

使用字体定义文件

¥Using a font definitions file

每次调用 localFont 或 Google 字体函数时,该字体都会作为一个实例托管在你的应用中。因此,如果需要在多个地方使用相同的字体,应该在一处加载,并在需要的地方导入相关的字体对象。这是使用字体定义文件完成的。

¥Every time you call the localFont or Google font function, that font will be hosted as one instance in your application. Therefore, if you need to use the same font in multiple places, you should load it in one place and import the related font object where you need it. This is done using a font definitions file.

例如,在应用目录根目录的 styles 文件夹中创建 fonts.ts 文件。

¥For example, create a fonts.ts file in a styles folder at the root of your app directory.

然后,指定字体定义,如下所示:

¥Then, specify your font definitions as follows:

ts
import { Inter, Lora, Source_Sans_3 } from 'next/font/google'
import localFont from 'next/font/local'

// define your variable fonts
const inter = Inter()
const lora = Lora()
// define 2 weights of a non-variable font
const sourceCodePro400 = Source_Sans_3({ weight: '400' })
const sourceCodePro700 = Source_Sans_3({ weight: '700' })
// define a custom local font where GreatVibes-Regular.ttf is stored in the styles folder
const greatVibes = localFont({ src: './GreatVibes-Regular.ttf' })

export { inter, lora, sourceCodePro400, sourceCodePro700, greatVibes }

你现在可以在代码中使用这些定义,如下所示:

¥You can now use these definitions in your code as follows:

tsx
import { inter, lora, sourceCodePro700, greatVibes } from '../styles/fonts'

export default function Page() {
  return (
    <div>
      <p className={inter.className}>Hello world using Inter font</p>
      <p style={lora.style}>Hello world using Lora font</p>
      <p className={sourceCodePro700.className}>
        Hello world using Source_Sans_3 font with weight 700
      </p>
      <p className={greatVibes.className}>My title in Great Vibes font</p>
    </div>
  )
}

为了更轻松地访问代码中的字体定义,你可以在 tsconfig.jsonjsconfig.json 文件中定义路径别名,如下所示:

¥To make it easier to access the font definitions in your code, you can define a path alias in your tsconfig.json or jsconfig.json files as follows:

你现在可以导入任何字体定义,如下所示:

¥You can now import any font definition as follows:

tsx
import { greatVibes, sourceCodePro400 } from '@/fonts'

预加载

¥Preloading

当在站点的页面上调用字体函数时,它不是全局可用的,也不是在所有路由上预加载的。相反,字体仅根据使用的文件类型预加载到相关路径上:

¥When a font function is called on a page of your site, it is not globally available and preloaded on all routes. Rather, the font is only preloaded on the related routes based on the type of file where it is used:

  • 如果它是 独特的页面,它将预加载到该页面的唯一路由上。

    ¥If it's a unique page, it is preloaded on the unique route for that page.

  • 如果它是 layout,它将预加载到布局包含的所有路由上。

    ¥If it's a layout, it is preloaded on all the routes wrapped by the layout.

  • 如果是 根布局,则会在所有路由上预加载。

    ¥If it's the root layout, it is preloaded on all routes.

版本变更

¥Version Changes

版本更改
v13.2.0@next/font 重命名为 next/font。不再需要安装。
v13.0.0@next/font 已添加。