I’m trying to get a custom font to load in my Flask-app. Whatever I try, it doesn’t seem to work.
The layout for my app looks like this:
Folder structure
- 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;
}
Upon loading the webpage, the font doesn’t change. Other things:
- The folder is found by the app (as in: no unresolved file path or directory), so that shouldn’t be the problem.
- Whenever I add a ‘font-family’ like Arial to the body in main.css, it DOES change the font on the webpage
I have looked at the following existing questions and tried to implement what was suggested in the answers, but it doesn’t seem to help. What am I missing?
- How to add custom font in python-flask?
- Python-Flask not accepting custom fonts
- How to add custom fonts to Flask?
Thanks.
>Solution :
The URL for the font is wrong in relation to where the CSS file is; URLs in stylesheets are resolved relative to the stylesheet’s location.
Since the CSS file is static/css/style.css, it should refer to ../fonts/Nunito-Italic-VariableFont_wght.ttf.
Your current static/fonts/Nunito-Italic-VariableFont_wght.ttf has the browser request static/css/static/fonts/... (which you can verify by looking at the Network inspector in your browser’s developer tools).
In addition, of course, you will need to refer to the font, e.g.
body {
font-face: Nunito;
}