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

如何在Flask中加载自定义字体?已尝试三种方法仍失败

Fixing Custom Font Loading in Flask

Let's break down what's going wrong in your attempts and walk through a reliable solution to get your custom font working in Flask.

First, Let's Spot the Key Issues in Your Tries

  1. Missing url() in @font-face src: All your CSS attempts forgot to wrap the font paths with url(), which is required syntax for browsers to locate the font files. Without it, the browser doesn't know it's supposed to fetch a file.
  2. Incorrect HTML structure: In your first two attempts, you placed the <link> tag for your stylesheet outside the <head> section—this isn't valid HTML and can cause loading issues.
  3. Unquoted paths in inline CSS: In attempt 3, you used url_for but didn't wrap the generated path in quotes, so the browser can't parse the font location correctly.

Step-by-Step Working Solution

1. Organize Your Project Structure (Clean & Maintainable)

Let's split static assets into separate folders for clarity:

your-flask-app/
├── app.py
├── static/
│   ├── css/
│   │   └── stylesheet.css
│   └── fonts/
│       ├── myfont.eot
│       ├── myfont.woff
│       ├── myfont.ttf
│       └── myfont.svg
└── templates/
    └── index.html

2. Correct the CSS File (static/css/stylesheet.css)

Use proper url() syntax, and reference the font files relative to the CSS file (since CSS is in css/, we go up one level to reach fonts/):

@font-face {
    font-family: 'myfont';
    /* Fallback for older IE */
    src: url('../fonts/myfont.eot');
    src: url('../fonts/myfont.eot?#iefix') format('embedded-opentype'),
         url('../fonts/myfont.woff') format('woff'),
         url('../fonts/myfont.ttf') format('truetype'),
         url('../fonts/myfont.svg#myfont') format('svg');
    /* Specify weight/style to avoid unexpected overrides */
    font-weight: normal;
    font-style: normal;
}

p {
    font-family: 'myfont', sans-serif; /* Add a fallback font */
    color: blue;
}

3. Fix the HTML Template (templates/index.html)

Make sure the stylesheet link is inside the <head> tag, and use url_for correctly:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Custom Font Test</title>
    <!-- Link stylesheet inside <head> -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/stylesheet.css') }}" type="text/css">
</head>
<body>
    <p>Test custom font display</p>
</body>
</html>

4. If You Prefer Inline CSS (Like Attempt 3)

If you want to embed the @font-face directly in the template, wrap the url_for output in quotes and use url():

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Custom Font Test</title>
    <style>
        @font-face {
            font-family: 'myfont';
            src: url("{{ url_for('static', filename='fonts/myfont.eot') }}");
            src: url("{{ url_for('static', filename='fonts/myfont.eot?#iefix') }}") format('embedded-opentype'),
                 url("{{ url_for('static', filename='fonts/myfont.woff') }}") format('woff'),
                 url("{{ url_for('static', filename='fonts/myfont.ttf') }}") format('truetype'),
                 url("{{ url_for('static', filename='fonts/myfont.svg#myfont') }}") format('svg');
            font-weight: normal;
            font-style: normal;
        }
        p {
            font-family: 'myfont', sans-serif;
            color: green;
        }
    </style>
</head>
<body>
    <p>prueba</p>
</body>
</html>

Troubleshooting Checks

  • Check Network Requests: Open your browser's DevTools (F12) → Network tab. Refresh the page and look for your font files. If you see a 404 error, double-check your file paths.
  • Clear Browser Cache: Old cached assets can prevent new fonts from loading—clear your cache or use incognito mode to test.
  • File Permissions: If deploying to a server, ensure the font files have read permissions (chmod 644 usually works).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:32:58