python - 如何在CSS文件中添加图片?我正在使用 python flask 进行网站开发

标签 python html css image flask

在使用 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/

相关文章:

python - 谁能帮我理解 Python 变量作用域?

python - 使用函数作为参数在 Python 中编写重试机制

html - 零边框在 html 中不起作用

html - 我将如何设计这样一个网站,其中垂直页面的一半是一种纹理,而另一种则不同?

javascript - 为什么即使一个组件的 z-index 值大于其他目标组件,CSS z-index 属性也不起作用?

Python PySpark : Count Number of Rows by Week w/Week Starting on Monday and Ending on Sunday

python - 在python中使用多个参数进行日志记录

html - 排列单选按钮

html - 可以将纯文本嵌入到 HTML 中吗?

html - Bootstrap 4在div的绝对中心对齐<a>标签