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

Flask应用加载自定义Nunito字体失败,排查无果求解决

Flask自定义字体加载失败解决方案

我在Flask应用中尝试加载自定义字体,但始终无法生效。应用的目录结构及各文件代码如下:

目录结构

- app.py
- static
  -- css
     --- main.css
  -- fonts
     --- Nunito-Italic-VariableFont_wght.ttf
- templates
  -- index.html
  -- base.html

app.py

from flask import Flask, render_template, url_for

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')


if __name__ == '__main__':
    app.run(debug=True)

index.html

{% extends 'base.html' %}

{% block title %}
Home
{% endblock %}

{% block body %}
<h1>Home</h1>
{% endblock %}

base.html

<!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <meta name = "viewport" content = "width=device-width, initial-scale=1">
    <link rel = "stylesheet" href = "{{ url_for('static', filename='css/main.css') }}">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    {% block body %}{% endblock %}
</body>
</html>

main.css(原代码)

@font-face {
    font-family: Nunito;
    src: url("static/fonts/Nunito-Italic-VariableFont_wght.ttf");
}

body {
    margin: 0;
    background-color: white;
    min-height: 100vh;
    background-size: cover;
}

已知情况

  • 应用能识别目录,不存在路径解析问题
  • 在main.css的body中设置Arial等系统字体时,网页字体正常变化

问题排查与修正

字体未生效的核心问题有两个:

  1. @font-face路径错误
    原CSS中使用的static/fonts/...是相对当前HTML页面的路径,而非相对于CSS文件的路径。因为main.css位于static/css/目录下,正确的相对路径应该是../fonts/...(回到static目录再进入fonts),或者使用绝对路径/static/fonts/...(更稳定,不受CSS文件位置影响)。

  2. 未指定使用自定义字体
    即使定义了@font-face,也需要在目标元素(如body)的样式中明确设置font-family,浏览器才会应用该字体。

修改后的main.css

@font-face {
    font-family: 'Nunito';
    /* 用相对路径或绝对路径均可,此处示例用绝对路径 */
    src: url('/static/fonts/Nunito-Italic-VariableFont_wght.ttf') format('truetype');
    /* 针对可变字体和斜体,明确属性确保渲染正确 */
    font-weight: 100 900;
    font-style: italic;
}

body {
    margin: 0;
    background-color: white;
    min-height: 100vh;
    background-size: cover;
    /* 指定使用自定义字体,并添加系统字体作为 fallback */
    font-family: 'Nunito', Arial, sans-serif;
}

额外验证步骤

  • 打开浏览器开发者工具(F12),检查网络标签,确认字体文件是否成功加载(状态码200)。
  • 若字体仍未生效,检查元素的font-family计算样式,确认自定义字体是否被正确应用(可能存在其他样式覆盖)。

内容的提问来源于stack exchange,提问作者getuser.name

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 22:03:30