我无法将
css
文件链接到 html 文件。
我正在使用 Visual Studio Code、Python 和 Flask 来执行此操作。
我的文件是这样的:
templates
home.html
style.css
app.py
home.html
<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Raleway:400, 600' rel='stylesheet' type='text/css'>
<link href='assets/style.css' rel='stylesheet' type='text/css'/>
</head>
<body>
...
</body>
样式.css
html, body {
margin: 0;
padding: 0;
}
header {
background-color: #333333;
position: fixed;
width: 100%;
z-index: 5;
}
h1 {
font-family: 'Times New Roman', Times, serif;
color:cadetblue
}
app.py
from flask import Flask, render_template
app = Flask(__name__, template_folder="templates")
@app.route("/home")
@app.route("/")
def index():
return render_template("home.html")
我尝试使用模板文件夹,但没有成功。
我尝试不使用模板文件夹,但没有成功。
它不会引发任何错误,但页面只是没有
css
样式,例如 h1 标签在默认字体下保持黑色,而它们应该是蓝色的 Times New Roman Font .
如有任何帮助,将不胜感激?🙂
在 Flask 中,您的 style.css 文件应位于“static”文件夹内。然后在你的 Html 文件中你应该像这样链接它:
<link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet" type="text/css"/>
在你的代码中,你使用了
assets/style.css
,但是模板中没有assets文件夹,所以找不到css。
您可以使用相对路径直接在 HTML 文件中连接 CSS 文件
<link href='style.css' rel='stylesheet' type='text/css'/>