【问题标题】:Custom font is not working in TailwindCSS & ReactJS project自定义字体在 TailwindCSS 和 ReactJS 项目中不起作用
【发布时间】:2022-01-04 06:56:52
【问题描述】:

我在我的 React/TypeScript/TailWind/NextJS 项目中使用自定义字体。 我将字体存储在/fonts 文件夹中为Glimer-Regular.ttf

然后在我的global.css 中声明如下。

@layer base {

    @font-face {
        font-family: '"Glimer"';
        src: url(../../fonts/Glimer-Regular.ttf) format('ttf');
    }
}


在我的tailwind.config.js 文件中,我添加了如下字体系列。

module.exports = {
    mode: 'jit',
    important: true,

    purge: ['./src/pages/**/*.{js,ts,jsx,tsx}'],
    darkMode: false,
    content: [],
    theme: {
        extend: {
            fontFamily: {
                glimer: ['"Glimer"']
            },

这应该可以,但字体仍然是默认字体并显示serif-400。我仍然可以在家庭部分看到Glimer,但字体似乎没有改变。 有什么我想念的吗?

【问题讨论】:

  • 字体系列名称有双引号。有可能这是问题吗? font-family: '"Glimer"';

标签: reactjs typescript fonts next.js tailwind-css


【解决方案1】:

我用两种不同的字体创建了这个例子..我希望你会喜欢它;-)!首先,将你想要的fonts下载到你的项目目录下的font文件夹中,下面是项目文件和文件夹的结构。这是我的解决方案:

example.js

function ExamplePage() {
  return (
    <div className="flex flex-col items-center justify-center h-screen gap-3">
      <h3 className="text-3xl font-custom1 text-blue-600">
        Sic Parvis Magna..
      </h3>
      <h3 className="text-3xl font-custom1 text-red-600">
        Per aspera ad astra..
      </h3>
      <h3 className="text-2xl font-custom2">
        In vino veritas, in aqua sanitas..
      </h3>
    </div>
  );
}

export default ExamplePage;

tailwind.config.js

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    fontFamily: {
      custom1: ["Custom-1", "sans-serif"],
      custom2: ["Custom-2", "sans-serif"],
    },

    extend: {},
  },
  plugins: [],
};

globals.css

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

@font-face {
  font-family: "Custom-1";
  src: url("/font/NewTegomin-Regular.ttf");
}

@font-face {
  font-family: "Custom-2";
  src: url("/font/Nosifer-Regular.ttf");
}

项目文件夹和文件结构:


输出


测试:“next”:“12.0.7”,“react”:“17.0.2”,“tailwindcss”:“^3.0.5”

【讨论】:

  • 谢谢!在我从global.css 中删除format('ttf'); 后,一切正常。
  • 不客气 ;-) 我很高兴 :-)
  • 如果您使用相同的字体但不同的粗细,这将如何改变。假设我们将它们全部导入@font-face,tailwind.config.js 会是什么样子?
猜你喜欢
  • 2018-11-23
  • 2020-09-10
  • 2019-07-17
  • 2018-12-01
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 2023-01-24
相关资源
最近更新 更多