首页 > 解决方案 > 外部css文件不会加载

问题描述

我正在关注 youtube 教程,但我的 CSS 不会加载。我尝试更改路径并重置 chrome 中的缓存。我不知道我可以改变什么来让它工作。其他一切都在工作我已经看过其他一些类似的帖子,但我在任何对我有用的帖子中都找不到答案。使用 VS 2019,Python 3.8

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 head %}
    <h1>Templated</h1>
{% endblock %}

{% block body %}
    <body>Templates</body>
{% endblock %}

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" type="text/css" herf="{{ url_for('static', filename='/css/main.css') }}" >
    {% block head %}{% endblock %}
</head>
<body>
    {% block body %}
    <link rel="stylesheet" type="text/css" herf="{{ url_for('static', filename='/css/main.css') }}">
    {% endblock %}
</body>
</html

main.css

body {
    color: blue;
    margin: 0;
    font-family: sans-serif;
}
h1 {
    color: red;
    margin: 0;
    font-family: sans-serif;
}

路径C:\Users\username\OneDrive\Programming\Visual Studio 2019\Flask Introduction\static\css\main.css

标签: pythonhtmlcssflask

解决方案


在您的base.htmllink标签中,删除/路径中的第一个/css/main.css( => css/main.css) 并更改为此并检查它是否有效:

  <link rel="stylesheet" type="text/css" herf="{{ url_for('static', filename='css/main.css') }}">

你不应该使用relative path那个absolute


推荐阅读