./app/fonts.ts
import { Montserrat, Open_Sans } from 'next/font/google'
export const montserrat = Montserrat({
subsets: ['latin'],
variable: '--font-montserrat',
display: 'swap',
});
export const open_sans = Open_Sans({
subsets: ['latin'],
variable: '--font-open-sans',
display: 'swap',
});
按照官方文档,我导入了字体并将它们添加到根布局中的 <body>
标签中:
.app/layout.tsx
import {montserrat, open_sans} from './fonts'
import "./globals.css";
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`${montserrat.variable} ${open_sans.variable} antialiased`}>
{children}
</body>
</html>
);
}
但是,有些东西不起作用。
.app/page.tsx
import {montserrat} from "./fonts";
export default function Home() {
return (
<>
<h1 className={`${montserrat.className}`}>Hello World</h1>
</>
);
}
.app/globals.css
h1 {
font-family: var(--font-open-sans);
}
h6 {
font-family: var(--font-montserrat);
}
为什么我的字体没有被应用?我要补充一点,我已经阅读了官方文档,但即使严格遵循,它也充其量是缺乏的。任何帮助将不胜感激。
app/layout.ts
:
// add this to <body>:
<body className={`${montserrat.variable} ${open_sans.variable}`}>
...
</body>
然后在 CSS 文件中使用该变量:
h1 {
font-family: var(--font-open-sans);
}
h6 {
font-family: var(--font-montserrat);
}
文档:https://nextjs.org/docs/app/api-reference/components/font#css-variables