You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js引入Gilroy本地字体后TailwindCSS样式不生效问题

解决Gilroy字体在TailwindCSS中无法修改颜色、字重及默认Thin的问题

问题核心原因

  1. Tailwind默认样式与next/font生成的字体类权重冲突,导致字重、颜色类无法生效
  2. 未给全局文本设置默认字重,浏览器自动取用了你定义的第一个字重(Thin 100)

解决方案

1. 配置Tailwind,将Gilroy设为默认字体

修改tailwind.config.ts,把Gilroy加入字体族,确保字重映射匹配你引入的字体文件:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {
      fontFamily: {
        sans: ['Gilroy', 'sans-serif'],
      },
      fontWeight: {
        thin: '100',
        regular: '400',
        bold: '700',
      },
    },
  },
  plugins: [],
}

2. 改用next/font的变量模式(更兼容Tailwind)

修改layout.tsx,通过variable选项生成CSS变量,替代直接给body添加className:

import type { Metadata } from "next";
import localFont from "next/font/local";
import "./globals.css";

const gilroy = localFont({
  src: [
    {
      path: "./fonts/gilroy/Gilroy-Thin.ttf",
      weight: "100",
      style: "normal",
    },
    {
      path: "./fonts/gilroy/Gilroy-ThinItalic.ttf",
      weight: "100",
      style: "italic",
    },
    {
      path: "./fonts/gilroy/Gilroy-Regular.ttf",
      weight: "400",
      style: "normal",
    },
    {
      path: "./fonts/gilroy/Gilroy-RegularItalic.ttf",
      weight: "400",
      style: "italic",
    },
    {
      path: "./fonts/gilroy/Gilroy-Bold.ttf",
      weight: "700",
      style: "normal",
    },
    {
      path: "./fonts/gilroy/Gilroy-BoldItalic.ttf",
      weight: "700",
      style: "italic",
    },
  ],
  variable: '--font-gilroy',
});

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Description",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en" className={gilroy.variable}>
      <body className="font-sans">{children}</body>
    </html>
  );
}

3. 重置全局默认样式,设置默认字重

修改app/globals.css,给body和默认标签设置基础样式,覆盖浏览器默认:

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

@layer base {
  body {
    @apply font-sans font-normal text-gray-900; /* 默认字重400,颜色可自定义 */
  }

  h1, h2, h3, h4, h5, h6 {
    @apply font-bold; /* 标题默认加粗,可按需调整 */
  }
}

验证效果

完成以上修改后重启开发服务器,现在应该可以正常使用Tailwind的font-bold、text-red-500等类,且文本默认不再是Thin字重。

内容的提问来源于stack exchange,提问作者Taha Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:27:06