在使用 Python Flask 之前一切正常。现在我尝试将我的 HTML 页面与 Python Flask 连接起来。 CSS 工作正常,但是当我在 CSS 文件中定义图像时,图像不再加载到网站中。相反,它显示错误 404。
python app.py 代码
from flask import Flask, render_template, url_for
app = Flask(__name__ , static_url_path='/static')
@app.route('/')
def index():
return render_template('/intro.html')
if __name__ == '__main__':
app.run(debug=True)
HTML 代码:-
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<title>NewliFit</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
<link rel="stylesheet" href="{{ url_for('static',filename='css/owl.carousel.css') }}">
<link rel="stylesheet" href="{{ url_for('static',filename='css/owl.carousel.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename = 'css/owl.theme.default.css') }}">
<link rel="stylesheet" href="{{ url_for('static',filename='css/firstone.css') }}">
</head>
<body>
<div class="main">
<div class="cover-image">
<div class="menu">
<div class="leftmenu">
CSS文件
@charset "utf-8";
/* CSS Document */
*{
margin: 0px ;
padding: 0px ;
}
/* ------------cover image -------------*/
.cover-image {
background-image: url({{ url_for('static',filename = '/images/cover4.jpg')}});
background-size: 100% 100%;
width: 100%;
height: 110vh;
}
请帮忙。
最佳答案
您正在 CSS 文件中使用 url_for,但它不起作用。您需要在 HTML 文件中指定背景图片的网址,或在您的 CSS 中指定正确的网址。
因此,要么将其添加到您的 CSS 中:
background-image: url('/static/images/cover4.jpg')}});
或者将 HTML 文件中的封面图像 div 更改为:
<div class="cover-image" style="background-image: url({{ url_for('static',filename = '/images/cover4.jpg')}});">
除非您计划定期更改您的静态文件夹(或您的封面图片),否则我建议您采用第一种方法,以确保您将样式和语义分开。
关于python - 如何在CSS文件中添加图片?我正在使用 python flask 进行网站开发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58008638/